-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcontext.go
49 lines (39 loc) · 962 Bytes
/
context.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
38
39
40
41
42
43
44
45
46
47
48
49
package context
import (
"context"
. "github.com/g-airport/go-infra/auth"
"github.com/google/uuid"
"github.com/micro/go-micro/metadata"
)
const (
RequestID = "RequestID"
Token = "Token"
)
func SetUser(ctx context.Context, u User) context.Context {
return context.WithValue(ctx, "user", u)
}
func GetUser(ctx context.Context) *User {
return ctx.Value("user").(*User)
}
func NewContext(token string) context.Context {
ctx := metadata.NewContext(context.Background(), map[string]string{
Token: token,
})
return ctx
}
func NewUUID() string {
u, _ := uuid.NewUUID()
return u.String()
}
func RequestIDFromContext(ctx context.Context) string {
if s, ok := ctx.Value(RequestID).(string); ok {
return s
}
return ""
}
func WithRequestID(ctx context.Context, requestID ...string) context.Context {
if len(requestID) != 0 {
return context.WithValue(ctx, RequestID, requestID[0])
}
return context.WithValue(ctx, RequestID, NewUUID())
}