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
+8.4k Golang : Find relative luminance or color brightness
+11.1k Golang : Create S3 bucket with official aws-sdk-go package
+6.2k Golang : Convert Chinese UTF8 characters to Pin Yin
+4.9k Golang : How to pass data between controllers with JSON Web Token
+32.6k Golang : Math pow(the power of x^y) example
+14.9k Golang : Find commonalities in two slices or arrays example
+13.5k Golang : Linear algebra and matrix calculation example
+13.3k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+18.8k Golang : Get download file size
+17.9k How to enable MariaDB/MySQL logs ?
+12.5k Elastic Search : Return all records (higher than default 10)
+13.7k Golang : Read XML elements data with xml.CharData example