Gofiber how to get the original path in middleware

Viewed 27

I have a gofiber routing like this

app.Use(func(c *fiber.Ctx) error {

  fmt.Println(c.Path()) <--- want this to get the original path name `/user/:id`

  return c.Next()
})
    
app.Get("/user/:id", func(c *fiber.Ctx) error {
    return c.SendString("Hello World")
})

When I call /user/1 the fmt print /user/1

but I want the fmt to print /user/:name how can I implement it

1 Answers

I've checked the code, you can access the original path with ctx.Route().Path:

package main

import (
    "fmt"
    "github.com/gofiber/fiber/v2"
)

func main() {
    router := fiber.New()
    router.Get("test/:id", func(ctx *fiber.Ctx) error {
        fmt.Printf("Registered route: %s, called route: %s\n", ctx.Route().Path, ctx.Path())
        return nil
    })
    if err := router.Listen(":7000"); err != nil {
        panic(err)
    }
}

Calling http://localhost:7000/test/test-id will print Registered route: /test/:id, called route: /test/test-id

Related