Skip to content

Commit

Permalink
added simple initial implementation of router in request context
Browse files Browse the repository at this point in the history
  • Loading branch information
Corné de Jong authored and AlexVulaj committed Jun 19, 2024
1 parent 10f71ea commit 1a848bf
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,9 @@ type routeConf struct {
// If true, the http.Request context will not contain the Route.
omitRouteFromContext bool

// if true, the the http.Request context will not contain the router
omitRouterFromContext bool

// Manager for the variables from host and path.
regexp routeRegexpGroup

Expand Down Expand Up @@ -207,6 +210,10 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
} else {
req = requestWithRouteAndVars(req, match.Route, match.Vars)
}

if !r.omitRouterFromContext {
req = requestWithRouter(req, r)
}
}
}

Expand Down Expand Up @@ -443,6 +450,7 @@ type contextKey int
const (
varsKey contextKey = iota
routeKey
routerKey
)

// Vars returns the route variables for the current request, if any.
Expand All @@ -464,6 +472,13 @@ func CurrentRoute(r *http.Request) *Route {
return nil
}

func CurrentRouter(r *http.Request) *Router {
if rv := r.Context().Value(routerKey); rv != nil {
return rv.(*Router)
}
return nil
}

// requestWithVars adds the matched vars to the request ctx.
// It shortcuts the operation when the vars are empty.
func requestWithVars(r *http.Request, vars map[string]string) *http.Request {
Expand All @@ -486,6 +501,11 @@ func requestWithRouteAndVars(r *http.Request, route *Route, vars map[string]stri
return r.WithContext(ctx)
}

func requestWithRouter(r *http.Request, router *Router) *http.Request {
ctx := context.WithValue(r.Context(), routerKey, router)
return r.WithContext(ctx)
}

// ----------------------------------------------------------------------------
// Helpers
// ----------------------------------------------------------------------------
Expand Down

0 comments on commit 1a848bf

Please sign in to comment.