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

Remove one allocation by foregoing context.WithValue #555

Merged
merged 1 commit into from
Nov 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"net"
"net/http"
"strings"
"time"
)

// URLParam returns the url parameter from a http.Request object.
Expand Down Expand Up @@ -92,6 +93,9 @@ type Context struct {

// methodNotAllowed hint
methodNotAllowed bool

// parentCtx is the parent of this one, for using Context as a context.Context directly
parentCtx context.Context
}

// Reset a routing context to its initial state.
Expand Down Expand Up @@ -139,6 +143,29 @@ func (x *Context) RoutePattern() string {
return replaceWildcards(routePattern)
}

type directContext Context

var _ context.Context = (*directContext)(nil)

func (d *directContext) Deadline() (deadline time.Time, ok bool) {
return d.parentCtx.Deadline()
}

func (d *directContext) Done() <-chan struct{} {
return d.parentCtx.Done()
}

func (d *directContext) Err() error {
return d.parentCtx.Err()
}

func (d *directContext) Value(key interface{}) interface{} {
if key == RouteCtxKey {
return (*Context)(d)
}
return d.parentCtx.Value(key)
}

// replaceWildcards takes a route pattern and recursively replaces all
// occurrences of "/*/" to "/".
func replaceWildcards(p string) string {
Expand Down
6 changes: 3 additions & 3 deletions mux.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package chi

import (
"context"
"fmt"
"net/http"
"strings"
Expand Down Expand Up @@ -78,9 +77,10 @@ func (mx *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
rctx = mx.pool.Get().(*Context)
rctx.Reset()
rctx.Routes = mx
rctx.parentCtx = r.Context()

// NOTE: r.WithContext() causes 2 allocations and context.WithValue() causes 1 allocation
r = r.WithContext(context.WithValue(r.Context(), RouteCtxKey, rctx))
// NOTE: r.WithContext() causes 2 allocations
r = r.WithContext((*directContext)(rctx))

// Serve the request and once its done, put the request context back in the sync pool
mx.handler.ServeHTTP(w, r)
Expand Down