1 回答

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超13個(gè)贊
我可以想到發(fā)生這種情況的兩個(gè)原因
您的服務(wù)器應(yīng)用程序無權(quán)訪問端口 443
您的瀏覽器正在嘗試通過端口 80 訪問您的服務(wù)器
由于標(biāo)記的標(biāo)簽無法解決第一個(gè)問題,因此此答案將涵蓋第二種情況。
出現(xiàn)此問題是因?yàn)槟J(rèn)情況下,當(dāng)您鍵入 www.domain.com 之類的地址時(shí),您的瀏覽器會(huì)嘗試使用端口 80 上的 http 協(xié)議聯(lián)系 url 域,并且Golang ListenAndServeTLS 在不使用 https 時(shí)返回?cái)?shù)據(jù)是一種已知行為瀏覽器
現(xiàn)在,如果您在瀏覽器中鍵入具有正確方案的完整 URL,例如https://www.domain.com瀏覽器將通過端口 443 接近服務(wù)器并啟動(dòng)與服務(wù)器的 TLS 握手,從而呈現(xiàn)正確的數(shù)據(jù)。
現(xiàn)在,您知道這一點(diǎn),但您的用戶不知道。每次嘗試僅使用您的域作為 URL 訪問您的 Web 應(yīng)用程序時(shí),如果您的用戶收到 SSL 握手錯(cuò)誤的通知,這將是非常令人沮喪的。
為了避免這個(gè)問題,您可以使用端口:80(或 8080)上的服務(wù)器啟動(dòng) go 例程,使用以下簡(jiǎn)單代碼將所有請(qǐng)求重定向到端口 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)
}
我希望它對(duì)干杯有幫助,
- 1 回答
- 0 關(guān)注
- 195 瀏覽
添加回答
舉報(bào)