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
+4.1k Golang : Display packages names during compilation
+9.2k Generate Random number with math/rand in Go
+14.8k Golang : Get sub string example
+24.4k Golang : Get executable name behind process ID example
+7.9k Golang : Populate or initialize struct with values example
+6.9k Golang : Append and add item in slice
+8.7k Golang : Test a slice of integers for odd and even numbers
+15.7k Golang : XML to JSON example
+3.8k Golang : Calculate a pip value and distance to target profit example
+7.4k Golang : Count leading or ending zeros(any item of interest) example
+4.7k Fix fatal error: evacuation not done in time problem
+12.5k Golang : Tutorial on loading GOB and PEM files