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
+17.2k Golang : Read binary file into memory
+25.1k Golang : Calculate future date with time.Add() function
+72.5k Golang : How to return HTTP status code?
+8.1k Golang : Timeout example
+12.8k Golang : Check if a file exist or not
+4.2k Python : Create Whois client or function example
+11.5k Golang : Get terminal width and height example
+15.9k Golang : Get future or past hours, minutes or seconds
+5.5k Android Studio : Hello World example
+8.9k Golang : Use regular expression to get all upper case or lower case characters example
+9.8k Golang : How to determine a prime number?
+8.6k Golang : How to check if a website is served via HTTPS