post image :date_long | 1 min Read

Go http.Redirect(...) http.StatusMovedPermanently 301

package main

import (
	"fmt"
	"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

func main() {
	http.HandleFunc("/", foo)
	http.HandleFunc("/bar", bar)
	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)

}

func bar(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("Bar, request method: %v\n", r.Method)
	http.Redirect(w, r, "/", http.StatusMovedPermanently) // status code: 301
}

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