gpt4 book ai didi

go - 如何从将x-real-ip和x-forward-for添加到 header 的负载平衡器获取gRPC中的客户端IP地址?

转载 作者:行者123 更新时间:2023-12-03 10:09:09 25 4
gpt4 key购买 nike

如何从将x-real-ip和x-forward-for添加到 header 的负载平衡器获取Go gRPC中的客户端IP地址?
“对等”库为我提供了唯一的负载均衡器IP。 (来自此答案:Get client's IP address from load balance server by X-Forwarded-For)
明确说明一下:我需要获取此信息的上下文在GRPC服务器处理程序内。它可能在拦截器中或在请求处理程序中:
例子:

func (s *myservice) MethodName(ctx context.Context, request *pb.MethodRequest) (*pb.MethodResponse, error) {

// How to get ip from ctx ?
// I have tryied peer but it gives me the loadbalancer ip
peer, ok := peer.FromContext(ctx)

return &pb.MethodResponse{Pong: "ok"}, nil
}

如果我也可以从拦截器中获取此消息,则可以...两种方法都对我有效。
func (a *MyInterceptor) Unary() grpc.UnaryServerInterceptor {
return func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (interface{}, error) {
log.Debug("--> My interceptor: " + info.FullMethod)


// How to get ip from ctx ?

return handler(ctx, req)
}
}

PS:我正在使用Kong作为负载均衡器。 https://docs.konghq.com/0.14.x/loadbalancing/

最佳答案

查看loadbalancer文档,您会发现X-Real-IP header 集https://docs.konghq.com/0.14.x/configuration/#real_ip_header
这应该在ctx的元数据中返回。不幸的是,我无法测试,但请告诉我它是否有效

func (a *MyInterceptor) Unary() grpc.UnaryServerInterceptor {
return func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (interface{}, error) {
log.Debug("--> My interceptor: " + info.FullMethod)


// How to get ip from ctx ?
var realIP string
m, ok := metadata.FromIncomingContext(ctx)
if ok {
realIP := md.Get("X-Real-IP")
}
// do what you need with realIP
return handler(ctx, req)
}
}

关于go - 如何从将x-real-ip和x-forward-for添加到 header 的负载平衡器获取gRPC中的客户端IP地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65912978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com