Home >Backend Development >Golang >How Can I Override Conflicting Server Headers in Go Middleware?
Overriding Server Headers in Go Middleware
Background
In Go, you can use middleware to handle and modify HTTP requests and responses. However, when adding a Server middleware to control HTTP headers, you may encounter issues with multiple Server headers being present in the response if other handlers also set the Server header.
Possible Solutions
type serverWriter struct { w http.ResponseWriter name string wroteHeader bool } func (s serverWriter) WriteHeader(code int) { if s.wroteHeader == false { s.w.Header().Set("Server", s.name) s.wroteHeader = true } s.w.WriteHeader(code) } func Server(h http.Handler, serverName string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { sw := serverWriter{ w: w, name: serverName, wroteHeader: false, } h.ServeHTTP(sw, r) }) }
Additional Notes
The above is the detailed content of How Can I Override Conflicting Server Headers in Go Middleware?. For more information, please follow other related articles on the PHP Chinese website!