Returning Status Codes In Golang

Here’s an overview of how to send HTTP status codes in Go. W represents a http.ResponseWriterreference, and r is a http.Request reference.

The following line tells the browser to redirect to the URL given (a 301 is a Moved Permanently redirect):

http.Redirect(w, r, "http://learntogoogleit.com/", 301)

Here is a standard Not Found error:

http.Error(w, http.StatusText(404), 404)

An Internal Server Error is indicated using a 500 status code:

http.Error(w, http.StatusText(500), 500)

The above examples use StatusText to retrieve standard error text, but you can set your own text if needed:

http.Error(w, "Too Many Requests", 429)