Fiber: 馃 Is it possible to transfer values from middleware to route?

Created on 27 Jul 2020  路  2Comments  路  Source: gofiber/fiber

Question description

I would like to know if it is possible to pass the value obtained in middleware to the route so that it can be rendered in response.

For example, in middleware we calculate how long it took to process the request and we want to render this number in the rendered HTML response using yours template engine

Example middleware:

func Timer() fiber.Handler {
    return func(c *fiber.Ctx) {
        start := time.Now()
        c.Next()
        stop := time.Now() 
                // and we want to render this value in response with other values
        c.Append("Server-Timing", fmt.Sprintf("Main;dur=%v", stop.Sub(start).String()))
    }
}

copy-n-pasted from here

馃 Question

Most helpful comment

@hugmouse Yes you can do this with Locals.

Something like this:

app.Use(func(c *fiber.Ctx) {
  c.Locals("user", "admin")
  c.Next()
})

app.Get("/admin", func(c *fiber.Ctx) {
  if c.Locals("user") == "admin" {
    c.Status(200).Send("Welcome, admin!")
  } else {
    c.SendStatus(403) // => 403 Forbidden
  }
})

Ref: https://docs.gofiber.io/ctx#locals

All 2 comments

@hugmouse Yes you can do this with Locals.

Something like this:

app.Use(func(c *fiber.Ctx) {
  c.Locals("user", "admin")
  c.Next()
})

app.Get("/admin", func(c *fiber.Ctx) {
  if c.Locals("user") == "admin" {
    c.Status(200).Send("Welcome, admin!")
  } else {
    c.SendStatus(403) // => 403 Forbidden
  }
})

Ref: https://docs.gofiber.io/ctx#locals

Thank you!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

GrigoriyMikhalkin picture GrigoriyMikhalkin  路  4Comments

Ivan-Feofanov picture Ivan-Feofanov  路  3Comments

faultable picture faultable  路  3Comments

renanbastos93 picture renanbastos93  路  3Comments

peterbourgon picture peterbourgon  路  4Comments