How to Use ResponseWriter in Go

Web
Use http.ResponseWriter in your handler function to set status codes, headers, and write the response body to the client.

Use http.ResponseWriter as the first argument in your HTTP handler function to write status codes, headers, and the response body directly to the client.

func handler(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "text/plain")
	w.Write([]byte("Hello, World!"))
}
  1. Define a handler function accepting w http.ResponseWriter and r *http.Request.
  2. Call w.WriteHeader(statusCode) to set the HTTP status before writing the body.
  3. Use w.Header().Set(key, value) to add custom headers.
  4. Write the response content using w.Write([]byte("content")).