Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add response header to every handler without repeating the same line

Tags:

go

handler

I am writing a small website and for every page, I am putting a server name to its header:

func httpSignUp(rw http.ResponseWriter, req *http.Request) {
    rw.Header().Set("Server", SERVER_NAME)
}

I am wondering if there's a way that I can set http.ResponseWriter's default server name, so I don't have to use the same line over and over?

like image 376
Gon Avatar asked Dec 04 '22 01:12

Gon


1 Answers

Create a wrapper to set the header:

func wrap(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (
         w.Header().Set("Server", SERVER_NAME)
         h.ServeHTTP(w, r)
    })
}

Wrap individual handlers

http.Handle("/path", wrap(aHandler)(
http.Handle("/another/path", wrap(anotherHandler))

or the root handler passed to ListenAndServe:

log.Fatal(http.ListenAndServe(addr, wrap(rootHandler))
like image 151
Bayta Darell Avatar answered Dec 06 '22 15:12

Bayta Darell