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
+9.8k Golang : Check if user agent is a robot or crawler example
+9.9k Golang : Test a slice of integers for odd and even numbers
+7.9k Golang : Sort words with first uppercase letter
+13.9k Golang : concatenate(combine) strings
+4.7k HTTP common errors and their meaning explained
+14.4k Golang : Send email with attachment(RFC2822) using Gmail API example
+17.9k Golang : Check if a directory exist or not
+18.9k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+19.1k Golang : Delete item from slice based on index/key position
+10.3k Generate Random number with math/rand in Go
+4.9k Golang : PGX CopyFrom to insert rows into Postgres database