Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set HTTP status code on http.ResponseWriter

Tags:

go

People also ask

How do you set a status code in HTTP response?

Methods to Set HTTP Status Code Sr.No. This method sets an arbitrary status code. The setStatus method takes an int (the status code) as an argument. If your response includes a special status code and a document, be sure to call setStatus before actually returning any of the content with the PrintWriter.

How can I get status code from HTTP status?

To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response. status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error. Copied!

What is the status code in HTTP?

An HTTP status code is a server response to a browser's request. When you visit a website, your browser sends a request to the site's server, and the server then responds to the browser's request with a three-digit code: the HTTP status code.


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!"))
}

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


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

full list here