1 回答

TA貢獻1842條經驗 獲得超13個贊
我可以想到發生這種情況的兩個原因
您的服務器應用程序無權訪問端口 443
您的瀏覽器正在嘗試通過端口 80 訪問您的服務器
由于標記的標簽無法解決第一個問題,因此此答案將涵蓋第二種情況。
出現此問題是因為默認情況下,當您鍵入 www.domain.com 之類的地址時,您的瀏覽器會嘗試使用端口 80 上的 http 協議聯系 url 域,并且Golang ListenAndServeTLS 在不使用 https 時返回數據是一種已知行為瀏覽器
現在,如果您在瀏覽器中鍵入具有正確方案的完整 URL,例如https://www.domain.com瀏覽器將通過端口 443 接近服務器并啟動與服務器的 TLS 握手,從而呈現正確的數據。
現在,您知道這一點,但您的用戶不知道。每次嘗試僅使用您的域作為 URL 訪問您的 Web 應用程序時,如果您的用戶收到 SSL 握手錯誤的通知,這將是非常令人沮喪的。
為了避免這個問題,您可以使用端口:80(或 8080)上的服務器啟動 go 例程,使用以下簡單代碼將所有請求重定向到端口 443:
// redir is a net.Http handler which redirects incoming requests to the
// proper scheme, in this case being https
func redir(w http.ResponseWriter, req *http.Request) {
hostParts := strings.Split(req.Host, ":")
http.Redirect(w, req, "https://"+hostParts[0]+req.RequestURI, http.StatusMovedPermanently)
}
func main() {
// this go subroutine creates a server on :8080 and uses the redir handler
go func() {
err := http.ListenAndServe(":8080", http.HandlerFunc(redir))
if err != nil {
panic("Error: " + err.Error())
}
}()
http.ListenAndServeTLS(":"+Config.String("port"), Config.Key("https").String("cert"), Config.Key("https").String("key"), router)
}
我希望它對干杯有幫助,
- 1 回答
- 0 關注
- 192 瀏覽
添加回答
舉報