douhu8851 2016-06-17 09:51
浏览 29
已采纳

去ListenAndServeTLS握手

Currently. I have this following line (works pretty good)

http.ListenAndServeTLS(":"+Config.String("port"), Config.Key("https").String("cert"), Config.Key("https").String("key"), router)

The problem comes when I try to set the port to 443 instead of for example 8080. I get on my browser the following error (Chrome)

This site can’t provide a secure connection.

www.example.com sent an

invalid response. ERR_SSL_PROTOCOL_ERROR

I am not sure what I am doing wrong or if I am not supposed to run the server on the port 443?

  • 写回答

1条回答 默认 最新

  • dongxing4196 2016-06-17 14:17
    关注

    I can think of two reasons why this is happening

    • Your server application doesn't have access to port 443
    • Your browser is trying to reach your server on port 80

    Since the first issue can't be solved by the marked tags, this answer will cover the second case.

    This problem happens because by default, when you type an address like www.domain.com, your browser tries to contact the url domain using the http protocol on port 80 and it's a known behavior that Golang ListenAndServeTLS returns data when not using https in the browser

    Now, if you type in your browser the full URL with the proper scheme like https://www.domain.com the browser will approach the server by the port 443 and start the TLS handshake with your server, thus rendering the correct data.

    Now, you know this, but not your users. It would be really frustrating to your users to be notified by a SSL handshake error every time they try to access your web application using only your domain as URL.

    In order to avoid this problem you could start a go routine with a server on port :80 (or 8080) that redirects all requests to port 443 with this simple piece of code:

    // 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)
    }
    

    I hope it helped Cheers,

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?