Andrew
Andrew

Reputation: 835

Header Content-Type not set when ServeMux pattern has no trailing slash

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

Upvotes: 1

Views: 376

Answers (0)

Related Questions