golang中判断请求是http还是https-用于获取当前访问地址

如果使用了nginx反向代理,那么需要确保反代中传入了下面的headers参数 X-Forwarded-Proto

location / {
    proxy_pass http://your_upstream_server;
    proxy_set_header X-Forwarded-Proto $scheme;
}

可以判断这个header来确认是否https

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    proto := r.Header.Get("X-Forwarded-Proto")
    if proto == "https" {
        fmt.Println("HTTPS request")
    } else {
        fmt.Println("HTTP request")
    }
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

如果没有经过反代,那么可以直接使用下面的代码来确认,http.Request结构体的TLS字段判断请求是否使用了HTTPS协议。如果该字段不为nil,则说明请求使用了HTTPS协议;否则,说明请求使用了HTTP协议

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    if r.TLS != nil {
        fmt.Println("HTTPS request")
    } else {
        fmt.Println("HTTP request")
    }
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

综合一下,获取当前访问地址的函数

//获取当前访问的Host
func GetHost(r *http.Request) (Url string) {
    scheme := "http://"
    if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
        scheme = "https://"
    }
    return strings.Join([]string{scheme, r.Host}, "")
}

猜你喜欢

转载自blog.csdn.net/taoshihan/article/details/129273543