卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34194本站已运行391

如何防止Fiber自动注册HEAD路由?

如何防止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()
})
卓越飞翔博客
上一篇: 用 go 重写文件最快的方法是什么
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏