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
+15.7k Golang : Get and Set User-Agent examples
+18k Golang : Read a text file and replace certain words
+10.2k Golang : Get all upper case or lower case characters from string example
+2.1k Golang : Display packages names during compilation
+8.9k Golang : Convert slice to array
+2.1k JavaScript : Rounding number to decimal formats to display currency
+2.5k Golang : Check if one string(rune) is permutation of another string(rune)
+4.4k PHP : How to parse ElasticSearch JSON ?
+17.3k Golang : Remove characters from string example
+8.5k Golang : Determine if directory is empty with os.File.Readdir() function
+12.8k PHP : Convert(cast) int to double/float
+2.9k Golang : Detect sample rate, channels or latency with PortAudio