首頁  >  文章  >  後端開發  >  如何防止Fiber自動註冊HEAD路由?

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

WBOY
WBOY轉載
2024-02-06 09:33:03453瀏覽

如何防止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 a> 和 (*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刪除