Fiber: ๐Ÿž Status code is not being set in a middleware function

Created on 17 May 2020  ยท  2Comments  ยท  Source: gofiber/fiber

Fiber version/commit
1.9.6

Issue description
When setting Status in conjunction with SendFile in a middleware function, in my case, the last handler for a catchall for nonexistent routes, the status is not being set, but instead defaulting to 200 which is default for SendFile. This is slightly different behavior from what is expected based on a different example from the docs. The html is SendFile is correct, but the status code is not.

Expected behavior
The response should contain the set status code. On the attached code snippet, the response code should be 404.

Steps to reproduce
Output using httpie

>> http -p h :3001/nonexistant
HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Encoding: gzip
Content-Length: 1025
Content-Type: text/html; charset=utf-8
Date: Sun, 17 May 2020 21:42:30 GMT
Last-Modified: Tue, 12 May 2020 20:40:50 GMT

Code snippet

package main

import "github.com/gofiber/fiber"

func main() {
  app := fiber.New()
  // .. all other middlewares

  // .. all routes

  // last handler before port
  // catchall 404
  app.Use(func(c *fiber.Ctx) {
    c.Status(404).SendFile("./pages/404.html")
  })

  app.Listen(port)
}
โ˜ข๏ธ Bug โ™ป Wait for Response

Most helpful comment

Welcome @securisec, thank you for your detailed bug report!

I reproduced the same result using SendFile(), this is because Fasthttp overwrites the status code. I applied a fix and this will ship with the next release in v1.10.

For the time being, you could use the following snippet:

app.Use(func(c *fiber.Ctx) {
    c.SendFile("./pages/404.html")
    c.Status(404)
})

I will leave this issue open until we tag v1.10 ๐Ÿ‘

All 2 comments

Thanks for opening your first issue here! ๐ŸŽ‰ Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

Welcome @securisec, thank you for your detailed bug report!

I reproduced the same result using SendFile(), this is because Fasthttp overwrites the status code. I applied a fix and this will ship with the next release in v1.10.

For the time being, you could use the following snippet:

app.Use(func(c *fiber.Ctx) {
    c.SendFile("./pages/404.html")
    c.Status(404)
})

I will leave this issue open until we tag v1.10 ๐Ÿ‘

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mewben picture mewben  ยท  3Comments

lucasmdomingues picture lucasmdomingues  ยท  3Comments

abowloflrf picture abowloflrf  ยท  4Comments

peterbourgon picture peterbourgon  ยท  4Comments

mhf-ir picture mhf-ir  ยท  3Comments