Skip to content

Commit

Permalink
Use ValueFromIncomingContext() to reduce allocations and copying (#723)
Browse files Browse the repository at this point in the history
  • Loading branch information
ash2k authored Aug 31, 2024
1 parent 8de7e4a commit 9774bef
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 11 deletions.
10 changes: 5 additions & 5 deletions interceptors/auth/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand All @@ -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")
}
Expand Down
9 changes: 3 additions & 6 deletions interceptors/realip/realip.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 9774bef

Please sign in to comment.