Home >Backend Development >Golang >How Can Go Middleware Control HTTP Headers to Prevent Duplicate Server Headers?

How Can Go Middleware Control HTTP Headers to Prevent Duplicate Server Headers?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-21 03:28:14528browse

How Can Go Middleware Control HTTP Headers to Prevent Duplicate Server Headers?

Controlling HTTP Headers from External Go Middleware

In this scenario, you have a Go middleware, Server, that you want to use to override any existing Server headers with a custom value. However, if any handlers down the request chain call w.Header().Add("Server", "foo"), it results in multiple Server headers in the response.

The intended behavior is to have Server middleware append its header value only after all other headers have been written. However, the semantics of ServeHTTP dictate that headers must be written before the call completes.

Using a Custom ResponseWriter

One workaround is to create a custom ResponseWriter that intercepts all header writes and inserts the Server header just before all headers are flushed. Here's an example:

type serverWriter struct {
    w           http.ResponseWriter
    name         string
    wroteHeader  bool
}

func (s serverWriter) WriteHeader(code int) {
    if !s.wroteHeader {
        s.w.Header().Set("Server", s.name)
        s.wroteHeader = true
    }
    s.w.WriteHeader(code)
}

func (s serverWriter) Write(b []byte) (int, error) {
    return s.w.Write(b)
}

func (s serverWriter) Header() http.Header {
    return s.w.Header()
}
Note: This approach requires an additional layer of indirection.

Updated Server Middleware

The updated Server middleware can then leverage this custom ResponseWriter:

// Server attaches a Server header to the response.
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)
    })
}

This solution ensures that the Server header is added at the appropriate time, regardless of when or where headers are added in the request chain.

For further insights, you can refer to https://kev.inburke.com/kevin/how-to-write-go-middleware/.

The above is the detailed content of How Can Go Middleware Control HTTP Headers to Prevent Duplicate Server Headers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn