中间件将针对每个请求执行,而无需指定安装路径

Node.js Express can insert a middleware with no mount path, and it gets executed for every request. Is there a way to accomplish that in 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();
});

Here's a basic example with Go's 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))
}

Middleware might be something like this:

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)
}

If you have a lot of middleware you want to chain, a package like alice can simplify it so you're not Wrapping(AllOf(YourMiddleware(r)))) like that. You could also write your own helper -

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)