context.go

 1package auth
 2
 3import "context"
 4
 5var (
 6	contextKey     = &struct{ string }{"auth"}
 7	ContextKeyUser = &struct{ string }{"user"}
 8)
 9
10// FromContext returns the auth from the context.
11func FromContext(ctx context.Context) Auth {
12	if auth, ok := ctx.Value(contextKey).(Auth); ok {
13		return auth
14	}
15	return nil
16}
17
18// WithContext returns a new context with the auth attached.
19func WithContext(ctx context.Context, auth Auth) context.Context {
20	return context.WithValue(ctx, contextKey, auth)
21}
22
23// UserFromContext returns the user from the context.
24func UserFromContext(ctx context.Context) User {
25	if u, ok := ctx.Value(ContextKeyUser).(User); ok {
26		return u
27	}
28	return nil
29}
30
31// WithUserContext returns a new context with the user attached.
32func WithUserContext(ctx context.Context, u User) context.Context {
33	return context.WithValue(ctx, ContextKeyUser, u)
34}