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
Convert Float32 to Float64 and Float64 to Float32
Struct Instantiation using new keyword
How to initialize a struct containing a slice of structs in Golang?
Concurrency in Golang
Go program to find Name Server (NS) record of a domain
Empty Interface Type in Go Programming Language
Golang panic recover example
Assign Default Value for Struct Field
Go program to find TXT records of a domain
How to Convert string to float type in Go?
Most Helpful This Week
Replace numbers by zero from stringGolang Get current Date and Time in EST, UTC and MST?Regular expression for matching HH:MM time format in GolangCatch values from GoroutinesHow pointer & and * and ** works in Golang?Regular expression to extract domain from URLSplit a character string based on change of characterHow to include and execute HTML template?How to find the type of the variable by different ways in Golang?Replace first occurrence of string using Regexp