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
+10.3k Golang : Meaning of omitempty in struct's field tag
+23.4k Golang : Check if element exist in map
+9.3k Golang : Convert(cast) string to int64
+5.8k Golang : Extract unicode string from another unicode string example
+4.6k Chrome : How to block socketloop.com links in Google SERP?
+43.1k Golang : Get hardware information such as disk, memory and CPU usage
+19.8k Golang : How to run your code only once with sync.Once object
+9.5k Golang : Copy map(hash table) example
+18.9k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+29.2k Golang : Save map/struct to JSON or XML file
+9.3k Golang : Create unique title slugs example
+18.6k Unmarshal/Load CSV record into struct in Go