Home >Backend Development >Golang >How to prevent Fiber from automatically registering HEAD routes?

How to prevent Fiber from automatically registering HEAD routes?

WBOY
WBOYforward
2024-02-06 09:33:03508browse

How to prevent Fiber from automatically registering HEAD routes?

Question content

Fiber v2 (https://go Fiber.io/) will automatically add a HEAD route for each GET route. Is it possible to prevent this?

I only want to register for GET. Actually, I only want to register those routes that I added explicitly.

Can this be done?


Correct answer


View(*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...)
}

and (*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...)
}

There is no way to prevent this behavior. All you can do is avoid using them and use the add method directly. For example, register a get route as follows:

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

Please note that (*app).use a> and (*group).use match all http verbs. You can remove head like this:

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,
})

Note: As soon as the head route is registered, it will panic because it is not included in requestmethods.

I don't know why you want to do this. Maybe a better option would be to use middleware to deny all head requests like this:

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

The above is the detailed content of How to prevent Fiber from automatically registering HEAD routes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete