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
+12.4k Golang : How to check if a string starts or ends with certain characters or words?
+36.1k Golang : Get file last modified date and time
+16.7k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+7.1k Golang : Squaring elements in array
+6.9k Golang : Pat multiplexer routing example
+12k Golang : Convert(cast) bigint to string
+6.8k Golang : Derive cryptographic key from passwords with Argon2
+6.1k Golang : Experimenting with the Rejang script
+19.4k Golang : Get RGBA values of each image pixel
+10.8k Golang : Resolve domain name to IP4 and IP6 addresses.
+16.5k Golang : How to implement two-factor authentication?
+7.6k Golang : Rot13 and Rot5 algorithms example