Obtain a schema of the current request URL

advertisements

In Ruby/Rack, I'm able to get the scheme of the current request URL from scheme#request. However, in Go, http.Request.URL.Scheme returns an empty string:

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "%#v\n", r.URL.Scheme) // Always shows empty string
}

How do I get scheme of the current request URL?


localhost is a special case for URL formation. It is going to be empty anyway if your client is localhost.

net.http package doc:

As a special case, if req.URL.Host is "localhost" (with or without a port number), then a nil URL and nil error will be returned.

The way to get required url/uri information is to get it from http.Request directly. For example:

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "%s\n", r.Host)
}