Keep context keys private

Instead, offer type safe accessors, as documented here:

https://pkg.go.dev/context#Context
This commit is contained in:
Conrad Hoffmann 2022-03-16 14:33:47 +01:00
parent 07c19a6f6c
commit 78bd2a9b84
3 changed files with 18 additions and 11 deletions

View file

@ -1,14 +1,13 @@
package auth
import (
"context"
"net/http"
)
var AuthCtxKey = &contextKey{"auth"}
type contextKey string
type contextKey struct {
name string
}
var authCtxKey contextKey = "auth"
type AuthContext struct {
AuthMethod string
@ -16,6 +15,15 @@ type AuthContext struct {
// TODO more?
}
func NewContext(ctx context.Context, a *AuthContext) context.Context {
return context.WithValue(ctx, authCtxKey, a)
}
func FromContext(ctx context.Context) (*AuthContext, bool) {
a, ok := ctx.Value(authCtxKey).(*AuthContext)
return a, ok
}
// Abstracts the authentication backend for the server.
type AuthProvider interface {
// Returns HTTP middleware for performing authentication.