Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the client IP address and user-agent in Golang gRPC?

Tags:

go

grpc

grpc-go

I set up a series of gRPC requests and responses which all work fine, but I'm stuck when I try to get the client IP address and user-agent who is calling my gRPC APIs.

I read the Go gRPC documentation and other sources, but didn't find much valuable information. Few of them are talking about gRPC in Golang.

Should I set up a key-value to store the IP address in the context when setting up the gRPC APIs?

like image 792
Felix Avatar asked Aug 08 '18 18:08

Felix


Video Answer


1 Answers

In Golang GRPC, you can use

func (UserServicesServer) Login(ctx context.Context, request *sso.LoginRequest) (*sso.LoginResponse, error) {
  p, _ := peer.FromContext(ctx)
  request.Frontendip = p.Addr.String()
  .
  .
}

But, do not forget import "google.golang.org/grpc/peer"

like image 166
mbdrian Avatar answered Sep 26 '22 15:09

mbdrian