【发布时间】:2017-04-11 03:13:14
【问题描述】:
在 Ruby/Rack 中,我可以get the scheme of the current request URL from scheme#request。然而,在 Go 中,http.Request.URL.Scheme 返回一个空字符串:
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%#v\n", r.URL.Scheme) // Always shows empty string
}
如何获取当前请求 URL 的 scheme?
【问题讨论】:
-
你可以检查
r.Proto它会根据文档返回HTTP/1.1或HTTP/2,但不确定它是否会改变HTTPS -
@YandryPozo
r.Proto只有在 Go 应用程序终止 TLS 本身时才会是HTTP/2,即使用http.ListenAndServeTLS()。 -
由于您使用 ListenAndServe 而不是 ListenAndServeTLS,因此您的方案可以安全地假定为 http。如果同时使用 tls 和非 tls 版本,则可以使用 r.TLS 并检查它是否为 null 以了解是否建立了 TLS。如果您的 Go 应用程序在反向代理后面运行,则几乎无法知道该方案是什么。
-
@MichaelKruglos 你的答案确实是这里唯一真正有效的答案,考虑到许多应用程序现在运行在 Web 服务(如 nginx)后面,在给定的环境中可能会或可能不会终止应用程序的 TLS。
标签: http go url url-scheme