Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Go (GoLang) Gorilla/Mux Set Response Code

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading