TLS を設定しましたが、動作します。nginx で http から https に書き換える方法は知っていますが、nginx はもう使用していません。これを Go で適切に行う方法がわかりません。
func main() {
certificate := "/srv/ssl/ssl-bundle.crt"
privateKey := "/srv/ssl/mykey.key"
http.HandleFunc("/", rootHander)
// log.Fatal(http.ListenAndServe(":80", nil))
log.Fatal(http.ListenAndServeTLS(":443", certificate, privateKey, nil))
}
func rootHander(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("To the moon!"))
}
これをうまく行うにはどうすればいいでしょうか?
ベストアンサー1
次のように、https へのリダイレクトを処理するハンドラーを作成します。
func redirectToTls(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://IPAddr:443"+r.RequestURI, http.StatusMovedPermanently)
}
次に、http トラフィックをリダイレクトします。
go func() {
if err := http.ListenAndServe(":80", http.HandlerFunc(redirectToTls)); err != nil {
log.Fatalf("ListenAndServe error: %v", err)
}
}()