【问题标题】:How to check if a request was made over HTTP or HTTPS [duplicate]如何检查请求是通过 HTTP 还是 HTTPS [重复]
【发布时间】:2019-11-08 22:31:24
【问题描述】:

如果对 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
    })
}

【问题讨论】:

  • 您的监听器无法接收 https 请求,因为它没有使用 TLS。接收请求的侦听器应该知道它是如何配置的并且可以适当地重定向。
  • 我的建议,这种服务使用 nginx。
  • 如果这是针对 Web 内容的,那是一回事,但如果它是针对 REST 调用的——那么不要费心做重定向——只是失败并出现适当的错误。 REST 的重定向是对资源的浪费。客户应该知道使用 https。

标签: go mux


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-25
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 2010-11-24
    • 2015-08-05
    • 1970-01-01
    相关资源
    最近更新 更多