您可以定义一个自定义类型,该类型将包装ResponseWriter并在写入所有标头之前插入Server标头,但要付出额外的间接层费用。这是一个例子:
type serverWriter struct { whttp.ResponseWriter name string wroteHeader bool}func (s serverWriter) WriteHeader(pre int) { if s.wroteHeader == false { s.w.Header().Set("Server", s.name) s.wroteHeader = true } s.w.WriteHeader(pre)}func (s serverWriter) Write(b []byte) (int, error) { return s.w.Write(b)}func (s serverWriter) Header() http.Header { return s.w.Header()}// 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) })}
我在这里写了更多有关此的内容。https://kev.inburke.com/kevin/how-to-write-go-middleware/
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)