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
+29.8k Golang : Get and Set User-Agent examples
+9.9k CodeIgniter : Load different view for mobile devices
+6.8k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+8.3k Your page has meta tags in the body instead of the head
+12.4k Elastic Search : Return all records (higher than default 10)
+19.3k Golang : How to count the number of repeated characters in a string?
+9.7k Golang : Load ASN1 encoded DSA public key PEM file example
+12.1k Golang : Split strings into command line arguments
+20.2k Swift : Convert (cast) Int to int32 or Uint32
+14.9k Golang : Search folders for file recursively with wildcard support
+7.6k Golang : Error reading timestamp with GORM or SQL driver
+17.4k Golang : Linked list example