5

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?

0

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.