I'm building a simple RESTful API using Fiber 2.44.0
and Go 1.20
. I'm currently testing if I can enforce the acceptable content for a given handler (something very common), but it looks like I'm doing something wrong, or fiber.Ctx.Accepts
doesn't quite work the way I'm expecting.
This is a very simple route I have defined. Notice the usage of ctx.Accepts
...but it doesn't really matter what Accept
HTTP header I use, all requests go through.
// app.go
func main() {
config := fiber.Config{
StrictRouting: true,
}
app := fiber.New(config)
app.Use(logger.New(), recover.New())
app.Get("/", handlers.RootHandler)
log.Fatal(app.Listen(":8080"))
}
// ============================================================================
// handlers/handlers.go
func RootHandler(ctx *fiber.Ctx) error {
ctx.Accepts(fiber.MIMETextPlain, fiber.MIMETextPlainCharsetUTF8)
ctx.Set(fiber.HeaderContentType, ctx.GetReqHeaders()[fiber.HeaderAccept])
return ctx.Status(fiber.StatusOK).SendString("Hello, world!")
}
Is there a way to avoid such behavior and configure the handlers/routes properly?
The signature of the func is:
func (c *Ctx) Accepts(offers ...string) string
It will return the acceptable offer from the offers you pass into this func. If the Accept
header in the request does not match any one of the offers, it returns an empty string (see the implementation). So if you want to enforce the acceptable content for a given handler, you can simply check whether the return value is an empty string:
func RootHandler(ctx *fiber.Ctx) error {
if offer := ctx.Accepts(fiber.MIMETextPlain, fiber.MIMETextPlainCharsetUTF8); offer == "" {
return ctx.SendStatus(fiber.StatusNotAcceptable)
}
// ...
}