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
+29.5k Golang : Get time.Duration in year, month, week or day
+28.7k Golang : Get first few and last few characters from string
+18.2k Golang : Example for RSA package functions
+11.4k SSL : The certificate is not trusted because no issuer chain was provided
+17.3k Golang : Clone with pointer and modify value
+7.6k Javascript : How to check a browser's Do Not Track status?
+11.3k Golang : Simple file scaning and remove virus example
+10.9k Golang : Fix - does not implement sort.Interface (missing Len method)
+36.1k Golang : Convert date or time stamp from string to time.Time type
+9.5k Random number generation with crypto/rand in Go
+8.7k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+9.6k Golang : Get current, epoch time and display by year, month and day