2016-05-31 56 views
8

我已經提出了TLS,它的工作原理。我知道如何在http上重寫nginx中的https,但我不再使用nginx。我不知道如何正確執行此操作。如何在Go中重寫/重定向從http到https?

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!")) 
} 

我該如何做到這一點?

回答

5

創建它處理重定向到HTTPS像處理程序:

func redirectTLS(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(redirectTLS)); err != nil { 
     log.Fatalf("ListenAndServe error: %v", err) 
    } 
}() 
+0

太謝謝你了! – Alex

+1

要重定向到的地址,最好使用'「https://」+ r.Host + r.RequestURI',這將避免讓您的主機名或IP地址被硬編碼。 –

1
Package main 
import (
    "fmt" 
    "net/http" 
) 
func redirectToHttps(w http.ResponseWriter, r *http.Request) { 
    // Redirect the incoming HTTP request. Note that "127.0.0.1:443" will only work if you are accessing the server from your local machine. 
    http.Redirect(w, r, "https://127.0.0.1:443"+r.RequestURI, http.StatusMovedPermanently) 
} 
func handler(w http.ResponseWriter, r *http.Request) { 
    fmt.Fprintf(w, "Hi there!") 
    fmt.Println(r.RequestURI) 
} 
func main() { 
    http.HandleFunc("/", handler) 
    // Start the HTTPS server in a goroutine 
    go http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil) 
    // Start the HTTP server and redirect all incoming connections to HTTPS 
    http.ListenAndServe(":8080", http.HandlerFunc(redirectToHttps)) 
} 
+0

謝謝你的幫助!我回答了幾個小時前的另一篇文章。祝你有美好的一天! – Alex

+0

這裏顯式的127.0.0.1地址有問題嗎?它可能需要接受域名,例如「https://」+ domain + r.RequestURI。 –

+0

另外,443是https的默認端口,可以省略。 –