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
+6.4k Golang : Extract sub-strings
+36.7k Golang : Save image to PNG, JPEG or GIF format.
+9.5k Golang : How to protect your source code from client, hosting company or hacker?
+19k Golang : Read input from console line
+7.4k Golang : alternative to os.Exit() function
+5.9k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+5k Javascript : How to get width and height of a div?
+9.9k Golang : Qt get screen resolution and display on center example
+28.8k Get file path of temporary file in Go
+26.8k Golang : How to check if a connection to database is still alive ?
+11.8k Golang : Concurrency and goroutine example
+5.9k Golang : Launching your executable inside a console under Linux