diff --git a/context.go b/context.go index d24b146..f3abab5 100644 --- a/context.go +++ b/context.go @@ -10,7 +10,11 @@ import ( ) func contextGet(r *http.Request, key string) (interface{}, error) { - val := r.Context().Value(key) + return valueFromContext(r.Context(), key) +} + +func valueFromContext(ctx context.Context, key string) (interface{}, error) { + val := ctx.Value(key) if val == nil { return nil, fmt.Errorf("no value exists in the context for key %q", key) } diff --git a/csrf.go b/csrf.go index 97a3925..56a05eb 100644 --- a/csrf.go +++ b/csrf.go @@ -19,7 +19,6 @@ const ( errorKey string = "gorilla.csrf.Error" skipCheckKey string = "gorilla.csrf.Skip" cookieName string = "_gorilla_csrf" - errorPrefix string = "gorilla/csrf: " ) var ( diff --git a/helpers.go b/helpers.go index 99005ee..f0495fe 100644 --- a/helpers.go +++ b/helpers.go @@ -1,6 +1,7 @@ package csrf import ( + "context" "crypto/rand" "crypto/subtle" "encoding/base64" @@ -14,7 +15,14 @@ import ( // a JSON response body. An empty token will be returned if the middleware // has not been applied (which will fail subsequent validation). func Token(r *http.Request) string { - if val, err := contextGet(r, tokenKey); err == nil { + return TokenFromContext(r.Context()) +} + +// TokenFromContext returns a masked CSRF token ready for passing into HTML template or +// a JSON response body. An empty token will be returned if the middleware +// has not been applied (which will fail subsequent validation). +func TokenFromContext(ctx context.Context) string { + if val, err := valueFromContext(ctx, tokenKey); err == nil { if maskedToken, ok := val.(string); ok { return maskedToken }