在没有指定装载路径的情况下,为每个请求执行中间件

时间:2015-11-12 02:21:02

标签: go

Node.js Express可以插入没有挂载路径的中间件,并为每个请求执行它。有没有办法在GO中实现这一目标?

var app = express();

// a middleware with no mount path; gets executed for every request to the app
app.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});

1 个答案:

答案 0 :(得分:2)

以下是Go net/http的基本示例:

func main() {
   r := http.NewServeMux()
   r.HandleFunc("/some-route", SomeHandler)

   // Wrap your *ServeMux with a function that looks like
   // func SomeMiddleware(h http.Handler) http.Handler   
   http.ListenAndServe("/", YourMiddleware(r))
}

中间件可能是这样的:

func YourMiddleware(h http.Handler) http.Handler {
   fn := func(w http.ResponseWriter, r *http.Request) {
       // Do something with the response
       w.Header().Set("Server", "Probably Go")
       // Call the next handler
       h.ServeHTTP(w, r)
   }

   // Type-convert our function so that it
   // satisfies the http.Handler interface
   return http.HandlerFunc(fn)
}

如果你想要链接很多中间件,像alice这样的包可以简化它,所以你不是Wrapping(AllOf(YourMiddleware(r))))那样的。{1}}。你也可以写自己的帮手 -

func use(h http.Handler, middleware ...func(http.Handler) http.Handler) http.Handler {
    for _, m := range middleware {
        h = m(h)
    }
    return h
}

// Example usage:
defaultRouter := use(r, handlers.LoggingHandler, csrf.Protect(key), CORSMiddleware)
http.ListenAndServe(":8000", defaultRouter)