Skip to content

Commit 9774bef

Browse files
authored
Use ValueFromIncomingContext() to reduce allocations and copying (#723)
1 parent 8de7e4a commit 9774bef

File tree

2 files changed

+8
-11
lines changed

2 files changed

+8
-11
lines changed

interceptors/auth/metadata.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@ import (
77
"context"
88
"strings"
99

10-
"github.com/grpc-ecosystem/go-grpc-middleware/v2/metadata"
1110
"google.golang.org/grpc/codes"
11+
"google.golang.org/grpc/metadata"
1212
"google.golang.org/grpc/status"
1313
)
1414

15-
var (
15+
const (
1616
headerAuthorize = "authorization"
1717
)
1818

@@ -22,11 +22,11 @@ var (
2222
// case-insensitive format (see rfc2617, sec 1.2). If no such authorization is found, or the token
2323
// is of wrong scheme, an error with gRPC status `Unauthenticated` is returned.
2424
func AuthFromMD(ctx context.Context, expectedScheme string) (string, error) {
25-
val := metadata.ExtractIncoming(ctx).Get(headerAuthorize)
26-
if val == "" {
25+
vals := metadata.ValueFromIncomingContext(ctx, headerAuthorize)
26+
if len(vals) == 0 {
2727
return "", status.Error(codes.Unauthenticated, "Request unauthenticated with "+expectedScheme)
2828
}
29-
scheme, token, found := strings.Cut(val, " ")
29+
scheme, token, found := strings.Cut(vals[0], " ")
3030
if !found {
3131
return "", status.Error(codes.Unauthenticated, "Bad authorization string")
3232
}

interceptors/realip/realip.go

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,16 +53,13 @@ func ipInNets(ip netip.Addr, nets []netip.Prefix) bool {
5353
}
5454

5555
func getHeader(ctx context.Context, key string) string {
56-
md, ok := metadata.FromIncomingContext(ctx)
57-
if !ok {
58-
return ""
59-
}
56+
vals := metadata.ValueFromIncomingContext(ctx, key)
6057

61-
if md[strings.ToLower(key)] == nil {
58+
if len(vals) == 0 {
6259
return ""
6360
}
6461

65-
return md[strings.ToLower(key)][0]
62+
return vals[0]
6663
}
6764

6865
func ipFromXForwardedFoR(trustedProxies []netip.Prefix, ips []string, idx int) netip.Addr {

0 commit comments

Comments
 (0)