-
-
Notifications
You must be signed in to change notification settings - Fork 4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to get the client IP address through ctx like in the gin framework? #3756
Comments
You can use |
What if i want to use it in the service logic layer? Apart from passing parameters. thanks @aishuchen |
type ServiceContext struct {
// ...
ClientIP string
}
// handler
func YouHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
svcCtx.ClientIP = httpx.GetRemoteAddr(r) // set in here
l :=logic.NewLogic(r.Context(), svcCtx)
err := l.Process(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, nil)
}
}
}
type YouLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
ClientIP string
}
// handler
func YouHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l :=logic.NewLogic(r.Context(), svcCtx)
l.ClientIP = httpx.GetRemoteAddr(r) // set in here
err := l.Process(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, nil)
}
}
}
// handler
func YouHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
clientIP := httpx.GetRemoteAddr(r)
ctx := context.WithValue(r.Context(), "clientIP", clientIP) // set in here
l :=logic.NewLogic(r.Context(), svcCtx)
err := l.Process(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, nil)
}
}
}
// method of YourLogic
func (l *YourLogic) Process(req *YouReq) error {
clientIP := l.ctx.Value("clientIP") // get in here
} And, use context in go-zero middleware, you can get client IP in all logics |
Awesome @aishuchen, but i solved it this way:
ctx := context.WithValue(r.Context(), "ip", httpx.GetRemoteAddr(r))
l := signin.NewXxxLogic(ctx, svcCtx)
l.ctx.Value("ip").(string) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In the Gin framework, you can get the client IP using
(ctx *gin.Context).ClientIP()
. Is there a similar method to achieve this in ZeroMicro? Currently, getting it viaip, _, err := net.SplitHostPort(r.RemoteAddr)
is a bit inconvenient.The text was updated successfully, but these errors were encountered: