2 Star 3 Fork 1

Allen / go-scaffold

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
request.go 2.01 KB
一键复制 编辑 原始数据 按行查看 历史
Allen 提交于 2020-08-25 16:02 . add http server
package server
import (
"errors"
"net"
"strings"
"github.com/gin-gonic/gin"
)
var ipMap []*net.IPNet
func init() {
maxCidrBlocks := []string{
"127.0.0.1/8", // localhost
"10.0.0.0/8", // 24-bit block
"172.16.0.0/12", // 20-bit block
"192.168.0.0/16", // 16-bit block
"169.254.0.0/16", // link local address
"::1/128", // localhost IPv6
"fc00::/7", // unique local address IPv6
"fe80::/10", // link local address IPv6
}
ipMap = make([]*net.IPNet, len(maxCidrBlocks))
for i, maxCidrBlock := range maxCidrBlocks {
_, cidr, _ := net.ParseCIDR(maxCidrBlock)
ipMap[i] = cidr
}
}
// isLocalAddress works by checking if the address is under private CIDR blocks.
// List of private CIDR blocks can be seen on :
//
// https://en.wikipedia.org/wiki/Private_network
//
// https://en.wikipedia.org/wiki/Link-local_address
func isPrivateAddress(address string) (bool, error) {
ipAddress := net.ParseIP(address)
if ipAddress == nil {
return false, errors.New("address is not valid")
}
for i := range ipMap {
if ipMap[i].Contains(ipAddress) {
return true, nil
}
}
return false, nil
}
// RemoteAddr get remote ip address
func RemoteAddr(c *gin.Context) string {
// Fetch header value
xRealIP := c.GetHeader("X-Real-Ip")
xForwardedFor := c.GetHeader("X-Forwarded-For")
// If both empty, return IP from remote address
if xRealIP == "" && xForwardedFor == "" {
var remoteIP string
// If there are colon in remote address, remove the port number
// otherwise, return remote address as is
if strings.ContainsRune(c.ClientIP(), ':') {
remoteIP, _, _ = net.SplitHostPort(c.ClientIP())
} else {
remoteIP = c.ClientIP()
}
return remoteIP
}
// Check list of IP in X-Forwarded-For and return the first global address
for _, address := range strings.Split(xForwardedFor, ",") {
address = strings.TrimSpace(address)
isPrivate, err := isPrivateAddress(address)
if !isPrivate && err == nil {
return address
}
}
// If nothing succeed, return X-Real-IP
return xRealIP
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/zakums06/go-scaffold.git
git@gitee.com:zakums06/go-scaffold.git
zakums06
go-scaffold
go-scaffold
v1.0.7

搜索帮助

344bd9b3 5694891 D2dac590 5694891