如何检查是否通过HTTP或HTTPS在golang中进行了请求

问题描述 投票:1回答:1

[如果尝试对HTTP进行api调用,我试图将API调用重定向到HTTPS,但是对于HTTP和HTTPS调用,r.URL.Scheme和r.TLS都为零

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/info", infoHandler).Methods("GET")   
    portString := fmt.Sprintf(":%s", getPorts())

    if cfenv.IsRunningOnCF() == true {
        r.Use(redirectTLS)
    }

    if err := http.ListenAndServe(portString, r); err != nil {
        panic(err)
    }

}

func redirectTLS(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        //if r.URL.Scheme != "https" {
        if r.TLS == nil {
            log.Info("Redirecting to HTTPS")
            //targetUrl := url.URL{Scheme: "https", Host: r.Host, Path: r.URL.Path, RawQuery: r.URL.RawQuery}
            http.Redirect(w, r, "https://"+r.Host+r.RequestURI, http.StatusMovedPermanently)
            //http.Redirect(w, r, targetUrl, http.StatusMovedPermanently)
            return
        }

        log.Info("Not Redirecting to HTTPS")
        next.ServeHTTP(w, r)
        return
    })
}
go mux
1个回答
0
投票

如果应用程序直接服务于HTTP和HTTPS,则该应用程序正在运行两个侦听器。配置在HTTP侦听器上运行的处理程序以重定向到HTTPS。正常配置HTTPS处理程序:

// Redirect HTTP to HTTPS
go func() {
        log.Fatal(http.ListenAndServe(httpPort, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    http.Redirect(w, r, "https://"+r.Host+r.RequestURI, http.StatusMovedPermanently)
    })))
    }()


// Run the application as normal on HTTPS.
r := mux.NewRouter()
r.HandleFunc("/info", infoHandler).Methods("GET")
log.Fatal(http.ListenAndServeTLS(httpsPport, certFile, keyFile, r))

无需使用重定向器包装现有的处理程序,因为HTTP和HTTPS请求使用不同的处理程序。

如果应用程序在反向代理后面运行,则将代理配置为将HTTP重定向到HTTPS。

© www.soinside.com 2019 - 2024. All rights reserved.