Skip to content

Commit

Permalink
Add method to get the user agent from the context if set
Browse files Browse the repository at this point in the history
  • Loading branch information
gmgigi96 committed Oct 22, 2021
1 parent 1c2ecf2 commit 9c1e428
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions pkg/ctx/agentctx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright 2018-2021 CERN
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// In applying this license, CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.

package ctx

import (
"context"

ua "github.com/mileusna/useragent"
"google.golang.org/grpc/metadata"
)

// ContextGetUserAgent returns the user agent if set in the given context.
// see https://github.com/grpc/grpc-go/issues/1100
func ContextGetUserAgent(ctx context.Context) (*ua.UserAgent, bool) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, false
}
userAgentLst, ok := md["user-agent"]
if !ok {
return nil, false
}
if len(userAgentLst) == 0 {
return nil, false
}
userAgent := ua.Parse(userAgentLst[0])
return &userAgent, true
}

0 comments on commit 9c1e428

Please sign in to comment.