-
Notifications
You must be signed in to change notification settings - Fork 786
/
extract_forwarded.go
53 lines (46 loc) · 1.35 KB
/
extract_forwarded.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
package util
import (
"context"
"google.golang.org/grpc/metadata"
)
// ipAddressesKey is key for the GRPC metadata where the IP addresses are stored
const ipAddressesKey = "extract-forwarded-x-forwarded-for"
// GetSourceIPsFromOutgoingCtx extracts the source field from the GRPC context
func GetSourceIPsFromOutgoingCtx(ctx context.Context) string {
md, ok := metadata.FromOutgoingContext(ctx)
if !ok {
return ""
}
ipAddresses, ok := md[ipAddressesKey]
if !ok {
return ""
}
return ipAddresses[0]
}
// GetSourceIPsFromIncomingCtx extracts the source field from the GRPC context
func GetSourceIPsFromIncomingCtx(ctx context.Context) string {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return ""
}
ipAddresses, ok := md[ipAddressesKey]
if !ok {
return ""
}
return ipAddresses[0]
}
// AddSourceIPsToOutgoingContext adds the given source to the GRPC context
func AddSourceIPsToOutgoingContext(ctx context.Context, source string) context.Context {
if source != "" {
ctx = metadata.AppendToOutgoingContext(ctx, ipAddressesKey, source)
}
return ctx
}
// AddSourceIPsToIncomingContext adds the given source to the GRPC context
func AddSourceIPsToIncomingContext(ctx context.Context, source string) context.Context {
if source != "" {
md := metadata.Pairs(ipAddressesKey, source)
ctx = metadata.NewIncomingContext(ctx, md)
}
return ctx
}