snippetgoCritical
How to set HTTP status code on http.ResponseWriter
Viewed 0 times
statushowresponsewritersethttpcode
Problem
How do I set the HTTP status code on an
I can see that requests normally have a status code of 200 attached to them.
http.ResponseWriter (e.g. to 500 or 403)?I can see that requests normally have a status code of 200 attached to them.
Solution
Use
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:
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!"))
}Code Snippets
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Something bad happened!"))
}Context
Stack Overflow Q#40096750, score: 255
Revisions (0)
No revisions yet.