gogo-httpgo-chi

go-chi router override middleware to set content type


I have a go API which so far has always returned JSON. I use chi router and set it up using middleware like this in my main function:

func router() http.Handler {

r := chi.NewRouter()
r.Use(render.SetContentType(render.ContentTypeJSON))
....

Now I want to return a file of various types in some functions. If I set the content type like this in my router function

func handleRequest(w http.ResponseWriter, r *http.Request) {
    fileBytes, err := ioutil.ReadFile("test.png")
    if err != nil {
        panic(err)
    }
    w.WriteHeader(http.StatusOK)
    w.Header().Set("Content-Type", "application/octet-stream")
    w.Write(fileBytes)
    return
}

Will that override the render setting for the content-type for this function?


Solution

  • Yes, you can set content type by simply setting Content-Type: header, but you need to do that before you actually call w.WriteHeader(http.StatusOK) like this:

    w.Header().Set("Content-Type", "application/octet-stream")
    w.WriteHeader(http.StatusOK)
    w.Write(fileBytes)
    

    otherwise you are making change after headers were written to the response and it will have no effect.