-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_id.go
37 lines (29 loc) · 811 Bytes
/
user_id.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package auth
import (
"context"
"errors"
)
// UserID is the identifier of the user.
type UserID string
func (s UserID) String() string {
return string(s)
}
type authContextKey string
const userIDKey = authContextKey("auth.user-id")
// GetUserID returns the user id from the context.
func GetUserID(ctx context.Context) (UserID, bool) {
s, ok := ctx.Value(userIDKey).(UserID)
return s, ok
}
// MustGetUserID returns the user id from the context or panics if it's not set.
func MustGetUserID(ctx context.Context) UserID {
s, ok := ctx.Value(userIDKey).(UserID)
if !ok {
panic(errors.New("missing user id in ctx"))
}
return s
}
// SetUserID sets the user id to the context.
func SetUserID(ctx context.Context, userID UserID) context.Context {
return context.WithValue(ctx, userIDKey, userID)
}