package main import ( "net/http" ) func RedirectHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") w.Header().Set("location", "http://www.yahoo.co.jp/") w.WriteHeader(http.StatusMovedPermanently) // 301 Moved Permanently } func main(){ http.HandleFunc("/rd", RedirectHandler) http.ListenAndServe(":3030", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
リダイレクト処理はhttp.Redirectでも出来る。
func RedirectHandler(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "http://www.yahoo.co.jp/", 301) }
違いとしてはこっちのhttp.Redirect関数だとaタグのHTMLが自動生成されて出力されるが初めの方はHTMLも自分で設定する必要がある点が違う。
リダイレクト処理でHTMLを返す必要はあまりないけどブラウザよってはリダイレクトしない場合もあるのでその場合への対応として念の為にHTMLを返すというぐらいなので簡単にやるならこっちがオススメ