post image January 6, 2022 | 2 min Read

Go http.Redirect(...) set redirection manually with headers

package main

import (
    "fmt"
    "html/template"
    "net/http"
)

// Redirects:
//  - StatusMultipleChoices   = 300 // RFC 7231, 6.4.1
//  - StatusMovedPermanently  = 301 // RFC 7231, 6.4.2
//  - StatusFound             = 302 // RFC 7231, 6.4.3
//  - StatusSeeOther          = 303 // RFC 7231, 6.4.4
//  - StatusNotModified       = 304 // RFC 7232, 4.1
//  - StatusUseProxy          = 305 // RFC 7231, 6.4.5
//  - StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
//  - StatusPermanentRedirect = 308 // RFC 7538, 3

var tpl *template.Template

func init() {
    tpl = template.Must(template.ParseFiles("index.gohtml"))
}

func main() {
    http.HandleFunc("/", foo)
    http.HandleFunc("/bar", bar)
    http.HandleFunc("/barred", barred)
    http.Handle("/favicon.ico", http.NotFoundHandler())
    http.ListenAndServe(":8080", nil)

}

// Options for <form> and POST method in particular
// 	- <form method="POST" enctype="multipart/form-data">
// 	- <form method="POST" enctype="multipart/x-www-form-urlencoded">
// 	- <form method="POST" enctype="text/plain">

func foo(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("Foo, request method: %v\n", r.Method)
    // io.WriteString(w, "foo was called ...")
}

func bar(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("Bar, request method: %v\n", r.Method)
    
	// http.Redirect(w, r, "/", http.StatusTemporaryRedirect) // status code: 307
	// Equivalent of the command above ^^^
	
	w.Header().Set("Location", "/")
	
	// Option 1.
	// 307 does not change the METHOD
	// w.WriteHeader(http.StatusTemporaryRedirect)
	
	// Option 2.
	// 303 change the METHOD to GET
	w.WriteHeader(http.StatusSeeOther)
}

func barred(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("Barred, request method: %v\n", r.Method)
    tpl.ExecuteTemplate(w, "index.gohtml", nil)
    // io.WriteString(w, "barred was called ...")
}


// <!DOCTYPE html>
// <html lang="en">
// <head>
//     <meta charset="UTF-8">
//     <title>Status StatusTemporaryRedirect 307 </title>
// </head>
// <body>


// <form method="POST" action="/bar" enctype="text/plain">
//     <label for="idx-f">First Name</label>
//     <input type="text" id="idx-f" name="first"><br>
//     <input type="submit">
// </form>

// </body>
// </html>
author image

Jan Toth

I have been in DevOps related jobs for past 6 years dealing mainly with Kubernetes in AWS and on-premise as well. I spent quite a lot …

comments powered by Disqus