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
Find out how many logical processors used by current process
GO Program to Swap Number Without Using Temporary Variables
Go program to find SRV service record of a domain
Golang program for implementation of Bubble Sort
Interface embedding another interface in Go Programming Language
Go program to reading plain text files
Most Helpful This Week
How to get Dimensions of an image type jpg jpeg png or gif ?How to collect information about garbage collection?How to split a string on white-space?Get Hours, Days, Minutes and Seconds difference between two dates [Future and Past]How to find out element position in slice?What is Rune? How to get ASCII value of any character in Go?Regular expression to extract filename from given path in GolangGet Set and Clear Session in GolangExample of Sscan vs Sscanf vs Sscanln from FMT PackageExample of Switch Case with Break in For Loop