Home >Backend Development >Golang >How to Determine the Scheme of the Current Request URL in Go?

How to Determine the Scheme of the Current Request URL in Go?

DDD
DDDOriginal
2024-11-03 17:35:03853browse

How to Determine the Scheme of the Current Request URL in Go?

Determine Scheme of 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:

  • If r.TLS is not nil, the scheme was HTTPS.
  • If r.TLS is nil, the scheme was HTTP.

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!

Statement:
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