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
+17.6k Golang : Find smallest number in array
+5.8k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+10.2k Golang : How to tokenize source code with text/scanner package?
+14.6k Golang : Rename directory
+6.6k Grep : How to grep for strings inside binary data
+32.3k Golang : Convert []string to []byte examples
+5.4k Golang : PGX CopyFrom to insert rows into Postgres database
+5.4k Golang : Get FX sentiment from website example
+5k JQuery : Calling a function inside Jquery(document) block
+26.4k Golang : Calculate future date with time.Add() function
+15.9k Golang : How to login and logout with JWT example
+7k Golang : How to setup a disk space used monitoring service with Telegram bot