How to set HTTP status code on http.ResponseWriter

Go

Go Problem Overview


How do I set the HTTP status code on an http.ResponseWriter (e.g. to 500 or 403)?

I can see that requests normally have a status code of 200 attached to them.

Go Solutions


Solution 1 - Go

Use http.ResponseWriter.WriteHeader. From the documentation:

> WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.

Example:

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusInternalServerError)
    w.Write([]byte("500 - Something bad happened!"))
}

Solution 2 - Go

Apart from WriteHeader(int) you can use the helper method http.Error, for example:

func yourFuncHandler(w http.ResponseWriter, r *http.Request) {

    http.Error(w, "my own error message", http.StatusForbidden)
    
    // or using the default message error
    
    http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}

http.Error() and http.StatusText() methods are your friends

Solution 3 - Go

w.WriteHeader(http.StatusInternalServerError)
w.WriteHeader(http.StatusForbidden)

full list here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick HView Question on Stackoverflow
Solution 1 - GoTim CooperView Answer on Stackoverflow
Solution 2 - GoYandry PozoView Answer on Stackoverflow
Solution 3 - GoMarsel NovyView Answer on Stackoverflow