gorilla / mux

Package gorilla/mux is a powerful HTTP router and URL matcher for building Go web servers with 🦍
https://gorilla.github.io
BSD 3-Clause "New" or "Revised" License
20.93k stars 1.85k forks source link

Feature route metadata #760

Closed cornejong closed 5 months ago

cornejong commented 6 months ago

What type of PR is this? (check all applicable)

Description

Added metadata to route. as proposed in #750 Documentation will be added uppon request.

Related Tickets & Documents

Added/updated tests?

Run verifications and test

cornejong commented 6 months ago

This pull request introduces metadata to route struct. The proposed changes allow attaching arbitrary metadata to routes, enabling more flexible and readable codebases.

Here's an example of how this feature can be used:

router.HandleFunc("/v1/product", handlerFunc).Metadata("authPolicy", "product.read")
// or an RBAC example
router.HandleFunc("/v1/product", handlerFunc).Metadata("allowedRoles", []Role{RoleAdmin, RoleManager, RoleEditor})

router.Use((next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        route := mux.CurrentRoute(r)

        if !route.MetadataContains("authPolicy") {
            next.ServeHTTP(w, r)
            return
        }

        authPolicy, err := route.GetMetadataValue("authPolicy")
        // or define a fallback value
        authPolicy := route.GetMetadataValueOr("authPolicy", "fallback_policy")

        // Enforce policy ...
    })
})

While authorization is a common use case, the .Metadata method opens up possibilities for various other configurations, such as caching, rate limiting or any other middleware for that matter. This addition aims to enhance the modularity and maintainability of applications by leveraging route metadata for various middleware configurations. The goal is to create clean and readable codebases where functionality can be abstracted into generalized middleware, keeping handlers clean and simple.

AlexVulaj commented 5 months ago

This change makes a lot of sense to me, thanks for the contribution!

AlexVulaj commented 5 months ago

Sorry for the "closed" notification - that was a misclick. PR is merged now!

cornejong commented 5 months ago

No problemo, Thanks for the merge! Always happy to contribute.