Golang : Set or add headers for many or different handlers
Problem :
In Golang, setting headers can be done easily with the Set() method.
At the moment, you are setting headers for each individual handler in such as manner :
func handlerA(w http.ResponseWriter, req *http.Request) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Set header for handler A."))
}
func handlerB(w http.ResponseWriter, req *http.Request) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Set header for handler B."))
}
Instead of setting header for each individual handler manually, you want to use a function to set the headers.
NOTE : This method can apply to Add headers as well
Solution :
Create a common SetHeaders()
function that will write to http.ResponseWriter. For example :
func SetHeaders(w http.ResponseWriter) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
}
func handlerA(w http.ResponseWriter, req *http.Request) {
SetHeaders(w)
w.Write([]byte("Set header for handler A."))
}
func handlerB(w http.ResponseWriter, req *http.Request) {
SetHeaders(w)
w.Write([]byte("Set header for handler B."))
}
See also : Golang : How to Set or Add Header http.ResponseWriter?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.6k Golang : Trim everything onward after a word
+5.2k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+9.3k Golang : Qt Yes No and Quit message box example
+8k Prevent Write failed: Broken pipe problem during ssh session with screen command
+5.9k Golang : Get missing location after unmarshal binary and gob decode time.
+12.4k Golang : Transform comma separated string to slice example
+10.9k Golang : How to determine a prime number?
+52.1k Golang : How to get struct field and value by name
+4.7k HTTP common errors and their meaning explained
+7.1k Golang : Example of custom handler for Gorilla's Path usage.
+14k Golang : Convert IP version 6 address to integer or decimal number
+5.6k Golang : Markov chains to predict probability of next state example