Golang : How to redirect to new page with net/http?
Problem :
You need to do a page redirect in Golang. How to do it ?
Solution :
Use net/http
package Redirect()
function.
For example :
Example 1:
package main
import (
"log"
"net/http"
)
func redirect(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://www.golang.org", 301)
}
func main() {
http.HandleFunc("/", redirect)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
Example 2:
func viewHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[len("/view/"):]
p, err := loadPage(title)
if err != nil {
http.Redirect(w, r, "/edit/"+title, http.StatusFound)
return
}
renderTemplate(w, "view", p)
}
References :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.5k Golang : Test input string for unicode example
+6k Javascript : How to replace HTML inside <div>?
+24.3k Golang : Upload to S3 with official aws-sdk-go package
+22.4k Golang : How to run Golang application such as web server in the background or as daemon?
+26.7k Golang : Convert(cast) string to uint8 type and back to string
+30.6k Golang : How to verify uploaded file is image or allowed file types
+18.6k Golang : How to remove certain lines from a file
+5.5k Golang : Get FX sentiment from website example
+32k Golang : How to convert(cast) string to IP address?
+8k Golang : Getting Echo framework StartAutoTLS to work
+6.5k Javascript : Generate random key with specific length