Home > Backend Development > Golang > How Do You Determine the Request URL Scheme in Go?

How Do You Determine the Request URL Scheme in Go?

DDD
Release: 2024-11-03 06:10:03
Original
943 people have browsed it

How Do You Determine the Request URL Scheme in Go?

Determining the Request URL Scheme in Go

In Rack middleware for Ruby, acquiring the scheme of the current request URL is straightforward using the scheme#request method. However, in Go, the http.Request.URL.Scheme field returns an empty string, leaving developers puzzled.

Unveiling the Scheme

The key to unlocking the request URL scheme in Go lies in recognizing that both HTTP and HTTPS requests must be handled. By employing both http.ListenAndServe() and http.ListenAndServeTLS() functions, we cater to both protocols.

TLS to the Rescue

HTTPS, being HTTP over TLS, provides a TLS property within *http.Request that discloses information about the TLS connection. By examining this property, we can discern the protocol used:

  • If r.TLS is non-null, the request was made via HTTPS.
  • If r.TLS is null, the request was made via HTTP.

Implementation

<code class="go">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>
Copy after login

This approach ensures that requests are handled seamlessly regardless of whether they are HTTP or HTTPS, providing a reliable mechanism for determining the request URL scheme.

The above is the detailed content of How Do You 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template