Home > Mobile >  Go (GoLang) Gorilla/Mux Set Response Code
Go (GoLang) Gorilla/Mux Set Response Code

Time:12-18

I'm having difficulty while trying to set the Response Code for a Gorilla Mux Route in Go. If I have a very simple route set up as

// dummy test route
router.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Headers", "*")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "POST, GET")
    w.Header().Set("Content-Type", "application/json")
    fmt.Fprintf(w, "{\"message\":\"OK\"}")
}).Methods("POST")

It seems to be working fine and returns a Status of 200 which is fine but if I try to set the response code manually like the below.

// dummy test route
router.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK) // added this to test
    w.Header().Set("Access-Control-Allow-Headers", "*")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "POST, GET")
    w.Header().Set("Content-Type", "application/json")
    fmt.Fprintf(w, "{\"message\":\"OK\"}")
}).Methods("POST")

Then it seems to have set the response code to 200 but it still coming through as an error when making a REST request

POST *url*/test net::ERR_FAILED 200

I am not sure why this is but is this not the correct way to set a response code?

CodePudding user response:

You have to write the status code in the end as the WriteHeader function writes to the response and flushes it.

// dummy test route
router.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Headers", "*")
        w.Header().Set("Access-Control-Allow-Origin", "*")
        w.Header().Set("Access-Control-Allow-Methods", "POST, GET")
        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusOK) // Set your code here, after setting your headers
        fmt.Fprintf(w, "{\"message\":\"OK\"}")
}).Methods("POST")
  • Related