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
+21.9k Golang : Convert string slice to struct and access with reflect example
+6.4k PHP : Proper way to get UTF-8 character or string length
+10.7k Golang : Simple File Server
+5.4k Javascript : Shuffle or randomize array example
+9.2k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?
+9.4k Golang : Terminate-stay-resident or daemonize your program?
+11.7k Golang : Simple file scaning and remove virus example
+19.9k Golang : Append content to a file
+12.8k Golang : Convert int(year) to time.Time type
+21.3k Golang : Create and resolve(read) symbolic links
+7.1k Golang : Squaring elements in array
+21.7k Golang : GORM create record or insert new record into database example