Home >Backend Development >Golang >How to Determine the Scheme of the Current Request URL in Go?
In Ruby/Rack, the scheme of the current request URL can be retrieved using scheme#request. However, in Go, http.Request.URL.Scheme returns an empty string. To obtain the scheme correctly, you must consider the following approach:
Serving HTTP and HTTPS protocols requires the simultaneous use of both http.ListenAndServe() and http.ListenAndServeTLS() with the same handler. By using only http.ListenAndServe(), you are listening exclusively for the HTTP protocol.
HTTPS, being HTTP over TLS, provides a TLS property in the http.Request object. This property returns a *tls.ConnectionState object, which contains information about the TLS employed for the request.
To determine the scheme utilized by the client, inspect the request's TLS property:
Here's an updated code example that demonstrates this approach:
<code class="go">package main import ( "fmt" "log" "net/http" "net/http/httputil" ) func handler(w http.ResponseWriter, r *http.Request) { // ... if r.TLS == nil { // the scheme was HTTP } else { // the scheme was HTTPS } } func main() { http.HandleFunc("/", handler) go func() { log.Fatal(http.ListenAndServeTLS(":8443", "localhost.crt", "localhost.key", nil)) }() log.Fatal(http.ListenAndServe(":8080", nil)) }</code>
The above is the detailed content of How to Determine the Scheme of the Current Request URL in Go?. For more information, please follow other related articles on the PHP Chinese website!