From 8d716e837d0300ef86d2092f5e93050b39e7187b Mon Sep 17 00:00:00 2001 From: fancl Date: Sat, 6 May 2023 16:15:04 +0800 Subject: [PATCH] add real ip take --- entry/http/context.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/entry/http/context.go b/entry/http/context.go index 55b06fb..72bc018 100644 --- a/entry/http/context.go +++ b/entry/http/context.go @@ -3,6 +3,7 @@ package http import ( "context" "encoding/json" + "net" "net/http" "os" "path" @@ -26,6 +27,21 @@ func (ctx *Context) reset(req *http.Request, res http.ResponseWriter, ps map[str ctx.req, ctx.res, ctx.params = req, res, ps } +func (c *Context) RealIp() string { + if ip := c.Request().Header.Get("X-Forwarded-For"); ip != "" { + i := strings.IndexAny(ip, ",") + if i > 0 { + return strings.TrimSpace(ip[:i]) + } + return ip + } + if ip := c.Request().Header.Get("X-Real-IP"); ip != "" { + return ip + } + ra, _, _ := net.SplitHostPort(c.Request().RemoteAddr) + return ra +} + func (ctx *Context) Request() *http.Request { return ctx.req }