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

旧城冷巷雨未停 提交于 2019-12-13 03:06:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!