How to Determine the Request URL Scheme in Go?

Barbara Streisand
Release: 2024-11-04 15:24:02
Original
272 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template