Responses
http.ResponseWriter
- The type
http.ResponseWriter
is an interface type that represents the response being sent back to the client
- It defines only three methods
Header()
: returns the header map and allows you to set the response header
WriteHeader(int)
: sets the response status code
Write([]byte) (int, error)
: writes the response body
Header()
and WriteHeader()
have to be called before writing the body
- The method
Write()
ensures that the response also implements the io.Writer
interface
- So all functions and methods working with
io.Writer
can also be used writing to the http.ResponseWriter
Examples
Hello, World!
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
w.Write([]byte("Hello, World!"))
}
Accept
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
accept := r.Header.Get("Accept")
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Your Accept header is: %s", accept)
}
Links