From 9774befc761e7df0e10b737175a2007997bddf90 Mon Sep 17 00:00:00 2001 From: Mikhail Mazurskiy <126021+ash2k@users.noreply.github.com> Date: Sat, 31 Aug 2024 14:32:39 +1000 Subject: [PATCH] Use ValueFromIncomingContext() to reduce allocations and copying (#723) --- interceptors/auth/metadata.go | 10 +++++----- interceptors/realip/realip.go | 9 +++------ 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/interceptors/auth/metadata.go b/interceptors/auth/metadata.go index ce9c45ab8..676d7b9d7 100644 --- a/interceptors/auth/metadata.go +++ b/interceptors/auth/metadata.go @@ -7,12 +7,12 @@ import ( "context" "strings" - "github.com/grpc-ecosystem/go-grpc-middleware/v2/metadata" "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) -var ( +const ( headerAuthorize = "authorization" ) @@ -22,11 +22,11 @@ var ( // case-insensitive format (see rfc2617, sec 1.2). If no such authorization is found, or the token // is of wrong scheme, an error with gRPC status `Unauthenticated` is returned. func AuthFromMD(ctx context.Context, expectedScheme string) (string, error) { - val := metadata.ExtractIncoming(ctx).Get(headerAuthorize) - if val == "" { + vals := metadata.ValueFromIncomingContext(ctx, headerAuthorize) + if len(vals) == 0 { return "", status.Error(codes.Unauthenticated, "Request unauthenticated with "+expectedScheme) } - scheme, token, found := strings.Cut(val, " ") + scheme, token, found := strings.Cut(vals[0], " ") if !found { return "", status.Error(codes.Unauthenticated, "Bad authorization string") } diff --git a/interceptors/realip/realip.go b/interceptors/realip/realip.go index bd0f2d20d..364fec2c9 100644 --- a/interceptors/realip/realip.go +++ b/interceptors/realip/realip.go @@ -53,16 +53,13 @@ func ipInNets(ip netip.Addr, nets []netip.Prefix) bool { } func getHeader(ctx context.Context, key string) string { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return "" - } + vals := metadata.ValueFromIncomingContext(ctx, key) - if md[strings.ToLower(key)] == nil { + if len(vals) == 0 { return "" } - return md[strings.ToLower(key)][0] + return vals[0] } func ipFromXForwardedFoR(trustedProxies []netip.Prefix, ips []string, idx int) netip.Addr {