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

How to prevent Fiber from automatically registering HEAD routes?

WBOY
Release: 2024-02-06 09:33:03
forward
521 people have browsed it

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...)
}
Copy after login

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...)
}
Copy after login

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!")
})
Copy after login

Please note that (*app).use 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,
})
Copy after login

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()
})
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template