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
+72.5k Golang : How to return HTTP status code?
+4.7k Swift : Get substring with rangeOfString() function example
+5.9k Golang : Calculate BMI and risk category
+16.7k Golang : Get command line arguments
+32.9k Golang : Integer is between a range
+3.9k Golang : Customize scanner.Scanner to treat dash as part of identifier
+18.9k Golang : How to get struct tag and use field name to retrieve data?
+10.6k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+6.5k Golang : Convert(cast) io.Reader type to string
+4.1k Golang : micron to centimeter example
+9.6k Golang : Replace a parameter's value inside a configuration file example
+14.9k Golang : convert string or integer to big.Int type