Judging whether the request is http or https in golang - used to obtain the current access address

If you use nginx reverse proxy, you need to ensure that the following headers parameter X-Forwarded-Proto is passed in the reverse generation

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

You can judge this header to confirm whether it is 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)
}

If it has not been reversed, you can directly use the following code to confirm that the TLS field of the http.Request structure determines whether the request uses the HTTPS protocol. If this field is not nil, it means that the request uses the HTTPS protocol; otherwise, it means that the request uses the HTTP protocol

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

In summary, the function to obtain the current access address

//获取当前访问的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}, "")
}

Guess you like

Origin blog.csdn.net/taoshihan/article/details/129273543