-
Notifications
You must be signed in to change notification settings - Fork 6
/
context.go
46 lines (40 loc) · 966 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
package interceptors
import (
"context"
"net"
"strings"
"google.golang.org/grpc/peer"
)
func PeerAddress(ctx context.Context) string {
p, ok := peer.FromContext(ctx)
if !ok {
return ""
}
host, _, err := net.SplitHostPort(p.Addr.String())
if err != nil {
return ""
}
if host == "" {
return "127.0.0.1"
}
return host
}
// ParseFullMethod returns service and method extracted from gRPC full method
// string, i.e., /package.service/method.
func ParseFullMethod(fullMethod string) (service, method string) {
name, found := strings.CutPrefix(fullMethod, "/")
if !found {
// Invalid format, does not follow `/package.service/method`.
return "", ""
}
service, method, found = strings.Cut(name, "/")
if !found {
// Invalid format, does not follow `/package.service/method`.
return "", ""
}
if strings.Contains(method, "/") {
// Invalid format, does not follow `/package.service/method`.
return "", ""
}
return service, method
}