gogo-fiber

How to prevent Fiber from auto registerting HEAD routes?


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

I want only the GETs to be registered. Actually, I want to register only those routes I add explicitly.

Is it possible to do this?


Solution

  • See the implementation of (*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 to avoid using them and use the Add method directly. For example, register a GET route like this:

    app.Add(fiber.MethodGet, "/", func(c *fiber.Ctx) error {
        return c.SendString("Hello, World!")
    })
    

    Please note that (*App).Use and (*Group).Use match all HTTP verbs. You can remove the HEAD method 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: it panics whenever a HEAD route is registered since it's not included in RequestMethods.


    I don't know why you want to do this. Maybe a better choice is to use a middleware to reject 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()
    })