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!"))
}
- Define a handler function accepting
w http.ResponseWriterandr *http.Request. - Call
w.WriteHeader(statusCode)to set the HTTP status before writing the body. - Use
w.Header().Set(key, value)to add custom headers. - Write the response content using
w.Write([]byte("content")).