问题
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?
回答1:
The way to get the IP address was already answered pretty well here: Correct way of getting Client's IP Addresses from http.Request (Golang)
As for the User-Agent header, you just need to parse the User-Agent
header like such: userAgent := response.Header.Get("User-Agent")
回答2:
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"
来源:https://stackoverflow.com/questions/51753461/how-can-i-get-the-client-ip-address-and-user-agent-in-golang-grpc