Home > Article > Backend Development > How to Determine the Request URL Scheme in Go?
Finding the Scheme of the Request URL in Go
In Ruby/Rack, retrieving the scheme of the current request URL is straightforward using the scheme#request method. However, in Go, http.Request.URL.Scheme yields an empty string.
Understanding the Issue
The reason behind the empty string is that Go supports serving both HTTP and HTTPS by default. When using only http.ListenAndServe(), you're solely serving HTTP. Conversely, using only http.ListenAndServeTLS() limits you to HTTPS.
Solution: Using TLS Connection State
To resolve this issue, leverage the TLS property of http.Request. This property provides a *tls.ConnectionState, revealing information about any TLS used in the request. By checking the TLS property, you can determine the scheme used by the client:
<code class="go">func handler(w http.ResponseWriter, r *http.Request) { if r.TLS == nil { fmt.Fprintf(w, "HTTP") } else { fmt.Fprintf(w, "HTTPS") } }</code>
Updated Main Function
Additionally, serve both HTTP and HTTPS protocols by using both listen functions:
<code class="go">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 Request URL Scheme in Go?. For more information, please follow other related articles on the PHP Chinese website!