如何在Golang gRPC中获取客户端IP地址和用户代理? [英] How can I get the client IP address and user-agent in Golang gRPC?

查看:1120
本文介绍了如何在Golang gRPC中获取客户端IP地址和用户代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了一系列可以正常运行的gRPC请求和响应,但是当我尝试获取正在调用我的gRPC API的客户端IP地址和用户代理时,我陷入了困境.

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.

我阅读了Go gRPC文档和其他资源,但没有找到太多有价值的信息.他们中很少有人谈论Golang中的gRPC.

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.

设置gRPC API时,是否应该设置一个键值以将IP地址存储在上下文中?

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

推荐答案

在Golang GRPC中,您可以使用

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()
.
.
}

但是,不要忘记导入"google.golang.org/grpc/peer"

这篇关于如何在Golang gRPC中获取客户端IP地址和用户代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆