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
+4.8k Golang : Get S3 or CloudFront object or file information
+18.9k Golang : How to get time from unix nano example
+6.7k Golang : Example of how to detect which type of script a word belongs to
+40.5k Golang : Convert string to array/slice
+8.6k Facebook : Getting the friends list with PHP return JSON format
+11.4k Android Studio : Highlight ImageButton when pressed on example
+32.9k Golang : Call a function after some delay(time.Sleep and Tick)
+7.4k How to show different content from website server when AdBlock is detected?
+22.3k Find and replace a character in a string in Go
+11.2k Golang : How to parse plain email text and process email header?
+16.5k Golang : Qt image viewer example
+6k Restart Apache or Nginx web server without password prompt