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
+7.3k Golang : File system scanning
+9.9k Golang : ffmpeg with os/exec.Command() returns non-zero status
+18.1k Golang : Check if a directory exist or not
+5.3k JavaScript/JQuery : Redirect page examples
+12.2k Golang : Split strings into command line arguments
+8.2k Golang : Get final or effective URL with Request.URL example
+24.6k Golang : Time slice or date sort and reverse sort example
+9k Golang : Inject/embed Javascript before sending out to browser example
+16.9k Golang : Read integer from file into array
+29.9k Golang : How to get HTTP request header information?
+10.6k Golang : Bubble sort example
+9.5k Golang : Convert(cast) string to int64