登录
首页 >  Golang >  Go问答

如何检查请求是通过 HTTP 还是 HTTPS 发出

来源:stackoverflow

时间:2024-04-21 12:06:27 217浏览 收藏

大家好,今天本人给大家带来文章《如何检查请求是通过 HTTP 还是 HTTPS 发出》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

如果对 http 进行 api 调用,我会尝试将 api 调用重定向到 https,但对于 http 和 https 调用,我在 r.url.scheme 和 r.tls 中都得到 nil

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

解决方案


如果应用程序直接提供 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。

以上就是《如何检查请求是通过 HTTP 还是 HTTPS 发出》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>