forked from grafana/grafana-plugin-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tenant.go
50 lines (39 loc) · 1023 Bytes
/
tenant.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
50
package tenant
import (
"context"
"google.golang.org/grpc/metadata"
)
const CtxKey = "tenantID"
type tenantKey struct{}
// IDFromContext returns tenant ID from context.
func IDFromContext(ctx context.Context) string {
v := ctx.Value(tenantKey{})
if v == nil {
return ""
}
return v.(string)
}
// WithTenant injects supplied tenant ID into context.
func WithTenant(ctx context.Context, tenantID string) context.Context {
ctx = context.WithValue(ctx, tenantKey{}, tenantID)
return ctx
}
// IDFromIncomingGRPCContext returns tenant ID from incoming gRPC metadata.
func IDFromIncomingGRPCContext(ctx context.Context) (string, bool) {
md, exists := metadata.FromIncomingContext(ctx)
if !exists {
return "", false
}
return idFromRequestMeta(md)
}
// idFromRequestMeta returns tenant ID from gRPC metadata.
func idFromRequestMeta(md metadata.MD) (string, bool) {
if md == nil {
return "", false
}
tid := md.Get(CtxKey)
if len(tid) > 0 && tid[0] != "" {
return tid[0], true
}
return "", false
}