为每个请求执行中间件,无需指定挂载路径

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();

});


米脂
浏览 235回答 1
1回答

慕妹3242003

这是 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))))那样了。您也可以编写自己的助手 -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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go