如何获取真实IP? #3339
leiwingqueen
started this conversation in
General
如何获取真实IP?
#3339
Replies: 1 comment 1 reply
-
是想获取客户端ip写入ctx传递吗?可以参考我自己写的获取requestid并传递的方式: package requestid
import (
"context"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/metadata"
"github.com/google/uuid"
)
const reqeustIdKey = "requestid"
// 获取请求id,从context获取,如果不存在就生成新的
func RequestId() log.Valuer {
return func(ctx context.Context) interface{} {
return GetOrGenerateRequestId(ctx)
}
}
func GetMdWithRequestId(ctx context.Context) metadata.Metadata {
var reqeustId string
md, ok := metadata.FromServerContext(ctx)
if ok {
reqeustId = md.Get(reqeustIdKey)
} else {
md = metadata.New()
}
if reqeustId == "" {
reqeustId = generateRequestId()
md.Set(reqeustIdKey, reqeustId)
}
return md
}
func GetOrGenerateRequestId(ctx context.Context) string {
var reqeustId string
md, ok := metadata.FromServerContext(ctx)
if ok {
reqeustId = md.Get(reqeustIdKey)
} else {
md = metadata.New()
}
if reqeustId == "" {
reqeustId = generateRequestId()
md.Set(reqeustIdKey, reqeustId)
}
return reqeustId
}
// 生成requestId
func generateRequestId() string {
return uuid.NewString()
}
// 在context中添加requestId
func ContextWithRequestId(ctx context.Context) context.Context {
md := GetMdWithRequestId(ctx)
ctx = metadata.NewServerContext(ctx, md)
return ctx
}
|
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
我们有一个服务在gin框架上跑,依赖gin框架的context,这个方法如何改为使用kratos框架的上下文实现
Beta Was this translation helpful? Give feedback.
All reactions