Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 [Bug]: Middleware Not Intercepting Requests When Route Registration Parameter Name Matches Group Name #3269

Closed
mohash25 opened this issue Jan 1, 2025 · 4 comments

Comments

@mohash25
Copy link

mohash25 commented Jan 1, 2025

Problem

When defining a route registration function with a parameter name identical to the fiber.Router group (e.g., api), the middleware does not intercept requests. This behavior is unexpected, as the middleware should consistently apply regardless of the parameter name.

Code Example

The following function works correctly:

func registerReservationAPI(appContainer app.App, cfg config.Config, router fiber.Router) { 
	reservationServiceGetter := reservationServiceGetter(appContainer)

	// Create reservation (transactional) with agency ID
	router.Post("/reservation/:agencyID", setTransaction(appContainer.DB()), CreateReservation(reservationServiceGetter, cfg)) 
}

However, renaming the router parameter to api causes the middleware to stop intercepting requests:

func registerReservationAPI(appContainer app.App, cfg config.Config, api fiber.Router) { 
	reservationServiceGetter := reservationServiceGetter(appContainer)

	// Create reservation (transactional) with agency ID
	api.Post("/reservation/:agencyID", setTransaction(appContainer.DB()), CreateReservation(reservationServiceGetter, cfg)) 
}

Environment

  • Go Version: 1.23.2
  • Fiber Version:v2.52.5
  • Operating System: Windows 10

How to Reproduce

  1. Define a Fiber route group with global middleware:

    api := router.Group(
        "/api/v1/agency",
        setUserContext,
        newAuthMiddleware([]byte(cfg.Server.Secret)),
    )
  2. Create a route registration function with fiber.Router as a parameter:

    func registerReservationAPI(appContainer app.App, cfg config.Config, api fiber.Router) { 
        reservationServiceGetter := reservationServiceGetter(appContainer)
    
        api.Post("/reservation/:agencyID", setTransaction(appContainer.DB()), CreateReservation(reservationServiceGetter, cfg)) 
    }
  3. Observe that the middleware is no longer triggered for /api/v1/agency/reservation/:agencyID.

  4. Rename the parameter to something other than api, e.g., router, and observe that the middleware now works as expected.


Expected Behavior

Middleware should intercept requests regardless of the parameter name used in route registration functions.

Fiber Version

v2.52.5

Code Snippet (optional)

package http

import (
	"fmt"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/recover"

	"gholi-fly-agancy/app"
	"gholi-fly-agancy/config"
)

func Run(appContainer app.App, cfg config.Config) error {
	// Initialize Fiber router
	router := fiber.New()
	router.Use(recover.New())
	// Initialize and use LoggerMiddleware
	loggerMiddleware, err := LoggerMiddleware(cfg.Logger)
	if err != nil {
		return err
	}
	router.Use(loggerMiddleware)
	// Apply global middlewares
	api := router.Group(
		"/api/v1/agency",
		setUserContext,
		newAuthMiddleware([]byte(cfg.Server.Secret)),
	)

	// Register Agency API
	registerAgencyAPI(appContainer, api)

	// Register Tour API
	registerTourAPI(appContainer, cfg, api)

	// Register Reservation API
	registerReservationAPI(appContainer, cfg, api)

	// Start the server
	return router.Listen(fmt.Sprintf(":%d", cfg.Server.HttpPort))
}

func registerAgencyAPI(appContainer app.App, router fiber.Router) {
	agencyServiceGetter := agencyServiceGetter(appContainer)

	// Create agency (transactional)
	router.Post("/", setTransaction(appContainer.DB()), CreateAgency(agencyServiceGetter))

	// Get agency by ID (non-transactional)
	router.Get("/:id", GetAgency(agencyServiceGetter))

	// Update agency by ID (transactional)
	router.Patch("/:id", setTransaction(appContainer.DB()), UpdateAgency(agencyServiceGetter))

	// Delete agency by ID (non-transactional)
	router.Delete("/:id", DeleteAgency(agencyServiceGetter))
}
func registerTourAPI(appContainer app.App, cfg config.Config, router fiber.Router) {
	tourServiceGetter := tourServiceGetter(appContainer)

	// Create tour (transactional)
	router.Post("/tour/:agencyID", setTransaction(appContainer.DB()), CreateTour(tourServiceGetter, cfg))

	// Get tour by ID (non-transactional)
	router.Get("/tour/:id", GetTour(tourServiceGetter))

	// Update tour by ID (transactional)
	router.Patch("/tour/:id", setTransaction(appContainer.DB()), UpdateTour(tourServiceGetter))

	// Delete tour by ID (non-transactional)
	router.Delete("/tour/:id", DeleteTour(tourServiceGetter))

	// List tours by agency (non-transactional)
	router.Get("/agency/:agencyID/tours", ListToursByAgency(tourServiceGetter))
}
func registerReservationAPI(appContainer app.App, cfg config.Config, api fiber.Router) {
	reservationServiceGetter := reservationServiceGetter(appContainer)

	// Create reservation (transactional) with agency ID
	api.Post("/reservation/:agencyID", setTransaction(appContainer.DB()), CreateReservation(reservationServiceGetter, cfg))
}


### Checklist:

- [X] I agree to follow Fiber's [Code of Conduct](https://github.com/gofiber/fiber/blob/master/.github/CODE_OF_CONDUCT.md).
- [X] I have checked for existing issues that describe my problem prior to opening this one.
- [X] I understand that improperly formatted bug reports may be closed without explanation.
Copy link

welcome bot commented Jan 1, 2025

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

@ReneWerner87
Copy link
Member

package main

import (
	"log"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/recover"
)

var logGrouoHandler = func(c *fiber.Ctx) error {
	log.Println("Group: Request URL:", c.OriginalURL(), "Route:", c.Route().Path, "Method:", c.Method())
	return c.Next()
}

var logChildHandler = func(c *fiber.Ctx) error {
	log.Println("Child: Request URL:", c.OriginalURL(), "Route:", c.Route().Path, "Method:", c.Method())
	return c.SendString("Hello, World!")
}

func main() {
	// Initialize Fiber router
	router := fiber.New()
	router.Use(recover.New())
	// Apply global middlewares
	api := router.Group(
		"/api/v1/agency",
		logGrouoHandler,
	)

	// Register Reservation API
	registerReservationAPI(api)

	// Start the server
	log.Fatal(router.Listen(":3000"))
}

func registerReservationAPI(api fiber.Router) {
	api.Get("/reservation/:agencyID", logChildHandler)
}

Test request to :
http://127.0.0.1:3000/api/v1/agency/reservation/111

image
image

@mohash25 can you try to prepare my simple example so that it is not too complex, but still shows the error ? i could not recreate it now

@ReneWerner87
Copy link
Member

@mohash25 i had to change the structure a bit because i don't have all the resources you used in your example

but i think it has to do with the same naming of the variables
where do you create the handler functions ? is it in the scope where the other router and api variables exist, so that it can come from overlapping?

@mohash25
Copy link
Author

mohash25 commented Jan 1, 2025

i found that the issue was with my debugger sorry to bother

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants