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 create an HTTP client in Go?
How do you set headers in an HTTP request with an HTTP client in Go?
Pass an Interface as an argument to a function in Go (Golang)
Golang program for implementation of Median of Medians
This sample program demonstrates how to create multiple goroutines and how the goroutine scheduler behaves with three logical processors.
Program in Golang to print Pyramid of Numbers
Most Helpful This Week
Anonymous Functions in GolangHow to convert Go struct to JSON?How to Remove duplicate values from Slice?Strip all white spaces, tabs, newlines from a stringSplit URL and Get Parameters from URLHow to fix race condition using Atomic Functions in Golang?Copy an array by value and reference into another arraySample program to create csv and write dataHow to copy a map to another map?Golang HTML parser