3 回答

TA貢獻1780條經驗 獲得超4個贊
Use必須在同一組下的所有路由之前聲明,而r.With允許您“內聯”中間件。
事實上,函數簽名是不同的。Use什么都不返回,With返回一個chi.Router.
假設您有一條路線并且只想向其中之一添加中間件,您可以使用r.With:
r.Route("/myroute", func(r chi.Router) {
r.Use(someMiddleware) // can declare it here
r.Get("/bar", handlerBar)
r.Put("/baz", handlerBaz)
// r.Use(someMiddleware) // can NOT declare it here
}
r.Route("/other-route", func(r chi.Router) {
r.Get("/alpha", handlerBar)
r.Put("/beta", handlerBaz)
r.With(someMiddleware).Get("/gamma", handlerQuux)
}
在第一個示例中,someMiddleware為所有子路由聲明,而在第二個示例中r.With允許您僅為/other-route/gamma路由添加中間件。

TA貢獻1811條經驗 獲得超6個贊
用例非常簡單,chi.Use注冊的中間件將在所有注冊到的路由處理程序之前運行Router
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("welcome"))
})
http.ListenAndServe(":3000", r)
例如:這里Logger的中間件將在所有注冊路由處理程序之前被調用。
而隨著chi.With您返回中間件將在其上運行的新路由,因此如果在返回Router的注冊中間件上注冊了任何路由,則注冊的中間件將運行。這里的用例非常具體假設如果你想為一組路由運行特定的中間件或者想要為特定的路由執行一些操作那么你可以使用chi.Use
r.Route("/articles", func(r chi.Router) {
r.With(paginate).Get("/", listArticles) // GET /articles
r.With(paginate).Get("/{month}-{day}-{year}", listArticlesByDate) // GET /articles/01-16-2017
r.Post("/", createArticle) // POST /articles
r.Get("/search", searchArticles) // GET /articles/search
// Regexp url parameters:
r.Get("/{articleSlug:[a-z-]+}", getArticleBySlug) // GET /articles/home-is-toronto
// Subrouters:
r.Route("/{articleID}", func(r chi.Router) {
r.Use(ArticleCtx)
r.Get("/", getArticle) // GET /articles/123
r.Put("/", updateArticle) // PUT /articles/123
r.Delete("/", deleteArticle) // DELETE /articles/123
})
})
在上面的例子中,paginate中間件只會被所有的文章調用,如果有任何中間件在主路由上注冊,那么其他路由/articles/的/{month}-{day}-{year}日間路由將不會被調用。chi.Withchi.Use
- 3 回答
- 0 關注
- 284 瀏覽
添加回答
舉報