-
Notifications
You must be signed in to change notification settings - Fork 282
/
grpcutil.go
62 lines (49 loc) · 1.7 KB
/
grpcutil.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
51
52
53
54
55
56
57
58
59
60
61
62
// Package grpcutil contains functions for interacting with gRPC.
package grpcutil
import (
"context"
"google.golang.org/grpc/metadata"
"google.golang.org/protobuf/proto"
)
// SessionIDMetadataKey is the key in the metadata.
const SessionIDMetadataKey = "sessionid"
// WithOutgoingSessionID appends a metadata header for the session ID to a context.
func WithOutgoingSessionID(ctx context.Context, sessionID string) context.Context {
return metadata.AppendToOutgoingContext(ctx, SessionIDMetadataKey, sessionID)
}
// SessionIDFromGRPCRequest returns the session id from the gRPC request.
func SessionIDFromGRPCRequest(ctx context.Context) (sessionID string, ok bool) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return "", false
}
sessionIDs := md.Get(SessionIDMetadataKey)
if len(sessionIDs) == 0 {
return "", false
}
return sessionIDs[0], true
}
// JWTMetadataKey is the key in the metadata.
const JWTMetadataKey = "jwt"
// WithOutgoingJWT appends a metadata header for the JWT to a context.
func WithOutgoingJWT(ctx context.Context, rawjwt string) context.Context {
return metadata.AppendToOutgoingContext(ctx, JWTMetadataKey, rawjwt)
}
// JWTFromGRPCRequest returns the JWT from the gRPC request.
func JWTFromGRPCRequest(ctx context.Context) (rawjwt string, ok bool) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return "", false
}
rawjwts := md.Get(JWTMetadataKey)
if len(rawjwts) == 0 {
return "", false
}
return rawjwts[0], true
}
// GetTypeURL gets the TypeURL for a protobuf message.
func GetTypeURL(msg proto.Message) string {
// taken from the anypb package
const urlPrefix = "type.googleapis.com/"
return urlPrefix + string(msg.ProtoReflect().Descriptor().FullName())
}