From 0a659fdad01c2df79d7f838c39cba4e96692b95b Mon Sep 17 00:00:00 2001 From: phith0n Date: Sun, 25 Dec 2022 04:05:52 +0800 Subject: [PATCH] add remote proto mechanism --- context.go | 24 ++++++++++++++++++++++++ gin.go | 6 ++++++ 2 files changed, 30 insertions(+) diff --git a/context.go b/context.go index 737e4d7a..c8fc9d6b 100644 --- a/context.go +++ b/context.go @@ -814,6 +814,30 @@ func (c *Context) RemoteIP() string { return ip } +func (c *Context) ClientProto() string { + var isTls = c.Request.TLS != nil + remoteIP := net.ParseIP(c.RemoteIP()) + if remoteIP == nil { + return "" + } + trusted := c.engine.isTrustedProxy(remoteIP) + + if trusted && c.engine.ForwardedByClientProto && c.engine.RemoteProtoHeaders != nil { + for _, headerName := range c.engine.RemoteProtoHeaders { + proto, valid := c.engine.validateHeader(c.requestHeader(headerName)) + if valid { + return proto + } + } + } + + if isTls { + return "https" + } else { + return "http" + } +} + // ContentType returns the Content-Type header of the request. func (c *Context) ContentType() string { return filterFlags(c.requestHeader("Content-Type")) diff --git a/gin.go b/gin.go index 35159d03..0697fb13 100644 --- a/gin.go +++ b/gin.go @@ -112,6 +112,8 @@ type Engine struct { // `(*gin.Context).Request.RemoteAddr`. ForwardedByClientIP bool + ForwardedByClientProto bool + // AppEngine was deprecated. // Deprecated: USE `TrustedPlatform` WITH VALUE `gin.PlatformGoogleAppEngine` INSTEAD // #726 #755 If enabled, it will trust some headers starting with @@ -136,6 +138,8 @@ type Engine struct { // network origins of list defined by `(*gin.Engine).SetTrustedProxies()`. RemoteIPHeaders []string + RemoteProtoHeaders []string + // TrustedPlatform if set to a constant of value gin.Platform*, trusts the headers set by // that platform, for example to determine the client IP TrustedPlatform string @@ -189,7 +193,9 @@ func New() *Engine { RedirectFixedPath: false, HandleMethodNotAllowed: false, ForwardedByClientIP: true, + ForwardedByClientProto: true, RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"}, + RemoteProtoHeaders: []string{"X-Forwarded-Proto"}, TrustedPlatform: defaultPlatform, UseRawPath: false, RemoveExtraSlash: false,