亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

中間件 chi.Use 與 chi.With 的區別

中間件 chi.Use 與 chi.With 的區別

Go
守著星空守著你 2022-12-19 21:40:03
使用 Chi router 設置中間件時chi.Use和之間有什么區別。chi.With
查看完整描述

3 回答

?
Helenr

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路由添加中間件。


查看完整回答
反對 回復 2022-12-19
?
qq_遁去的一_1

TA貢獻1725條經驗 獲得超8個贊

根據chi.Usechi.With的文檔。

使用將中間件處理程序附加到 Mux 中間件堆棧。

任何 Mux 的中間件堆棧將在搜索到特定處理程序的匹配路由之前執行,這提供了提前響應、更改請求執行過程或為下一個 http.Handler 設置請求范圍值的機會。

With 為端點處理程序添加內聯中間件。


查看完整回答
反對 回復 2022-12-19
?
楊魅力

TA貢獻1811條經驗 獲得超6個贊

讓我們看看如何chi.Usechi.With例子

用例非常簡單,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


查看完整回答
反對 回復 2022-12-19
  • 3 回答
  • 0 關注
  • 284 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號