首頁 > 後端開發 > Golang > 主體

如何防止Fiber自動註冊HEAD路由?

WBOY
發布: 2024-02-06 09:33:03
轉載
450 人瀏覽過

如何防止Fiber自動註冊HEAD路由?

問題內容

Fiber v2 (https://go Fiber.io/) 會自動為每個 GET 路由新增一個 HEAD 路由。 有可能阻止這種情況嗎?

我只想註冊 GET。實際上,我只想註冊那些我明確新增的路由。

可以這樣做嗎?


正確答案


查看(*app).get:

// get registers a route for get methods that requests a representation
// of the specified resource. requests using get should only retrieve data.
func (app *app) get(path string, handlers ...handler) router {
    return app.head(path, handlers...).add(methodget, path, handlers...)
}
登入後複製

(*group).get

// get registers a route for get methods that requests a representation
// of the specified resource. requests using get should only retrieve data.
func (grp *group) get(path string, handlers ...handler) router {
    grp.add(methodhead, path, handlers...)
    return grp.add(methodget, path, handlers...)
}
登入後複製

沒有辦法阻止這種行為。您所能做的就是避免使用它們並直接使用 add 方法。例如,註冊一個 get 路由,如下所示:

app.add(fiber.methodget, "/", func(c *fiber.ctx) error {
    return c.sendstring("hello, world!")
})
登入後複製

請注意(*app).use(*group).use 符合所有 http 動詞。您可以像這樣刪除 head 方法:

methods := make([]string, 0, len(fiber.defaultmethods)-1)
for _, m := range fiber.defaultmethods {
    if m != fiber.methodhead {
        methods = append(methods, m)
    }
}
app := fiber.new(fiber.config{
    requestmethods: methods,
})
登入後複製

注意:只要註冊 head 路由,它就會出現恐慌,因為它不包含在 requestmethods 中。

我不知道你為什麼要這樣做。也許更好的選擇是使用中間件來拒絕所有 head 請求,如下所示:

app.Use(func(c *fiber.Ctx) error {
    if c.Method() == fiber.MethodHead {
        c.Status(fiber.StatusMethodNotAllowed)
        return nil
    }
    return c.Next()
})
登入後複製

以上是如何防止Fiber自動註冊HEAD路由?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!