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
+16.9k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+85.2k Golang : How to convert character to ASCII and back
+7.9k Swift : Convert (cast) Character to Integer?
+8.7k Golang : Gonum standard normal random numbers example
+9.1k Facebook : Getting the friends list with PHP return JSON format
+6.3k Golang : Skip or discard items of non-interest when iterating example
+13.2k Golang : Activate web camera and broadcast out base64 encoded images
+18.8k Golang : Check if directory exist and create if does not exist
+18.1k Golang : Example for RSA package functions
+5.7k Golang : How to verify input is rune?
+16.2k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+3.2k Golang : Switch Redis database redis.NewClient