How do you set headers in an HTTP response in Go?
To set headers in an HTTP response in Go, you can use the http.ResponseWriter interface's Header() method to get the header map, and then use the Set() method to add or update headers.
Set headers in an HTTP response
Example
func handlerFunc(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, `{"message": "Hello, world!"}`)
}
In this example, the Content-Type header is set to application/json, indicating that the response will contain JSON data. The WriteHeader() method is then called to set the HTTP status code to 200 (OK). Finally, the fmt.Fprintln() function is used to write the response body to the http.ResponseWriter object.
Note that headers must be set before writing any data to the response body, as the headers are sent as part of the response's initial HTTP header.
Most Helpful This Week
How do you handle HTTP server shutdown gracefully in Go?
How do you handle HTTP server caching in Go?
How do you handle HTTP client server logging in Go?
How do you send an HTTP PATCH request in Go?
How do you set cookies in an HTTP request with an HTTP client in Go?
How do you read headers in an HTTP response in Go?
How do you create an HTTP client in Go?
How do you read cookies in an HTTP request with an HTTP client in Go?
How do you handle HTTP responses in Go?
How do you handle HTTP errors in Go?
Most Helpful This Week
Simple example of Map initialization in GoConvert Int data type to Int16 Int32 Int64How to use function from another file golang?Split URL and Get Parameters from URLHow to use a mutex to define critical sections of code and fix race conditions?How to remove symbols from a string in Golang?Regular Expression to get a string between parentheses in GolangRegular expression to validate email addressHow to Unmarshal nested JSON structure?Different ways to convert Byte Array into String