mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-15 21:06:39 +08:00
refactor: refactor make trust ip
This commit is contained in:
parent
53fbf4dbfb
commit
162a228e7c
17
gin.go
17
gin.go
@ -17,6 +17,7 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin/internal/bytesconv"
|
||||
"github.com/gin-gonic/gin/render"
|
||||
"github.com/gin-gonic/gin/utils"
|
||||
"golang.org/x/net/http2"
|
||||
"golang.org/x/net/http2/h2c"
|
||||
)
|
||||
@ -387,6 +388,7 @@ func (engine *Engine) Run(addr ...string) (err error) {
|
||||
}
|
||||
|
||||
func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) {
|
||||
var err error
|
||||
if engine.trustedProxies == nil {
|
||||
return nil, nil
|
||||
}
|
||||
@ -394,17 +396,10 @@ func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) {
|
||||
cidr := make([]*net.IPNet, 0, len(engine.trustedProxies))
|
||||
for _, trustedProxy := range engine.trustedProxies {
|
||||
if !strings.Contains(trustedProxy, "/") {
|
||||
ip := parseIP(trustedProxy)
|
||||
if ip == nil {
|
||||
return cidr, &net.ParseError{Type: "IP address", Text: trustedProxy}
|
||||
}
|
||||
|
||||
switch len(ip) {
|
||||
case net.IPv4len:
|
||||
trustedProxy += "/32"
|
||||
case net.IPv6len:
|
||||
trustedProxy += "/128"
|
||||
}
|
||||
trustedProxy, err = utils.MakeTrustIP(trustedProxy)
|
||||
}
|
||||
if err != nil {
|
||||
return cidr, err
|
||||
}
|
||||
_, cidrNet, err := net.ParseCIDR(trustedProxy)
|
||||
if err != nil {
|
||||
|
42
utils/ip.go
Normal file
42
utils/ip.go
Normal file
@ -0,0 +1,42 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"net"
|
||||
)
|
||||
|
||||
func parseIP(ip string) (net.IP, error) {
|
||||
parsedIP := net.ParseIP(ip)
|
||||
|
||||
if ipv4 := parsedIP.To4(); ipv4 != nil {
|
||||
return ipv4, nil
|
||||
}
|
||||
if parsedIP != nil{
|
||||
return parsedIP, nil
|
||||
}
|
||||
return nil, &net.ParseError{Type: "IP address", Text: ip}
|
||||
}
|
||||
|
||||
func MakeTrustIP(trustedIP string) (string, error) {
|
||||
ip, err := parseIP(trustedIP)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var mapRenderIP = map [int]func(trustIP string) string{
|
||||
net.IPv4len: func(trustIP string) string{
|
||||
return trustIP + "/32"
|
||||
},
|
||||
net.IPv6len: func(trustIP string) string{
|
||||
return trustIP + "/32"
|
||||
},
|
||||
}
|
||||
|
||||
fn, isExistKey := mapRenderIP[len(ip)]
|
||||
|
||||
if isExistKey != true{
|
||||
return "", &net.ParseError{Type: "IP address", Text: trustedIP}
|
||||
}
|
||||
|
||||
return fn(trustedIP), nil
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user