golang实现http middleware

https://justinas.org/writing-http-middleware-in-go#usecases

http.Handlerhttp.HandlerFunc

http.Handler

type Handler interface {
	ServeHTTP(ResponseWriter, *Request)
}

http.HandlerFunc

type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
	f(w, r)
}

结构体 实现 http.Handler

type SingleHost struct {
    handler     http.Handler
    allowedHost string
}

func (s *SingleHost) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    host := r.Host
    if host == s.allowedHost {
        s.handler.ServeHTTP(w, r)
    } else {
        w.WriteHeader(403)
    }
}
// handler := SingleHost{handler, allowedHost}

高阶函数

func SingleHost(handler http.Handler, allowedHost string) http.Handler {
    ourFunc := func(w http.ResponseWriter, r *http.Request) {
        host := r.Host
        if host == allowedHost {
            handler.ServeHTTP(w, r)
        } else {
            w.WriteHeader(403)
        }
    }
    return http.HandlerFunc(ourFunc)
}
// handler := SingleHost(handler, allowedHost)

github.com/justinas/alice:

it transforms
Middleware1(Middleware2(Middleware3(App)))
to
alice.New(Middleware1, Middleware2, Middleware3).Then(App)

type Constructor func(http.Handler) http.Handler

type Chain struct {
	constructors []Constructor
}

func New(constructors ...Constructor) Chain {
	return Chain{append(([]Constructor)(nil), constructors...)}
}

func (c Chain) Then(h http.Handler) http.Handler {
	for i := range c.constructors {
		h = c.constructors[len(c.constructors)-1-i](h)
	}

	return h
}
原文地址:https://www.cnblogs.com/elimsc/p/14979330.html