1

I have the simplest HTTP server:

package main

import (
    "net/http"
)

func handle(w http.ResponseWriter, r *http.Request) {
    // Calling http://localhost:10000/test/ will not panic
    // Calling http://localhost:10000/test WILL panic
    if r.Header.Get("Content-Type") == "" {
        panic("No Content-Type header found")
    }
}

func main() {
    http.HandleFunc("/test/", handle)
    err := http.ListenAndServe(":10000", nil)
    if err != nil {
        panic(err)
    }
}

The server will match both /test and /test/ like https://golang.org/pkg/net/http/#ServeMux indicates.

However, the URL without the trailing slash will not have the Content-Type set causing the panic in the code above. Am I missing something? Why does leaving off the trailing slash cause Content-Type header specifically to disappear? Other headers, like Accept, Cache-Control, etc., still show up.

Also, I am executing these requests via Postman.

It appears the default http mux handles the redirect using a 301 which Postman cannot handle. Executing the following CURL command:

curl -X POST 'http://localhost:10000/test' -H 'Accept: application/pdf' -H 'Content-Type:text/markdown' -w "%{http_code}"

prints 301

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Andrew
  • 815
  • 8
  • 17
  • 1
    A GET request should not have a `Content-Type` header because it has no body to have a content type. Also note that, per the linked docs, "If a subtree has been registered and a request is received naming the subtree root without its trailing slash, ServeMux **redirects that request** to the subtree root (adding the trailing slash)" (emphasis mine). So the request your handler actually receives is the same (the URL with the trailing slash). – Adrian Jul 15 '19 at 19:48
  • I neglected to specify that the request in question is a POST, because as you correctly stated, GETs don't pass Content-Type. And yes, the same handler gets executed in both cases. But in the case of `/test` the Content-Type header is NOT set. – Andrew Jul 15 '19 at 20:07
  • You never see the POST request for /test. You see the GET request for /test/ that the client sends when following the redirect. There's nothing wrong with your server, you just seem to be misunderstanding the client's behavior. Add -Lv to the curl command and remove the -w flag and it should become clear. – Peter Jul 15 '19 at 22:51
  • @Peter I realize that there's nothing wrong with the server, but should I expect, based on the go language documentation, to receive a 301? – Andrew Jul 16 '19 at 13:53
  • 1
    Yes, you should. Adrian quoted the relevant docs. – Peter Jul 16 '19 at 14:39
  • Sorry, I read `redirects` as `routes` somehow. Makes sense now. Sorry for wasting your time. – Andrew Jul 16 '19 at 17:08

0 Answers0