1 Star 0 Fork 0

Wsage / go-framework

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
network.go 1.04 KB
AI 代码解读
一键复制 编辑 原始数据 按行查看 历史
王少奇 提交于 2021-08-22 21:44 . 新增 相关辅助方法
package utils
import (
"fmt"
uuid "github.com/satori/go.uuid"
"net"
"net/http"
"strings"
)
func GetRequestIp(r *http.Request) string {
ips := r.Header.Get("X-Forwarded-For")
if ips == "" {
return strings.Split(ips, ",")[0]
}
ip := r.Header.Get("X-Real-IP")
if ip == "" {
// 当请求头不存在即不存在代理时直接获取ip
ip = strings.Split(r.RemoteAddr, ":")[0]
}
return ip
}
// 获取本机网卡IP
func GetLocalIP() (ipv4 string, err error) {
var (
addrs []net.Addr
addr net.Addr
ipNet *net.IPNet // IP地址
isIpNet bool
)
// 获取所有网卡
if addrs, err = net.InterfaceAddrs(); err != nil {
return
}
// 取第一个非lo的网卡IP
for _, addr = range addrs {
// 这个网络地址是IP地址: ipv4, ipv6
if ipNet, isIpNet = addr.(*net.IPNet); isIpNet && !ipNet.IP.IsLoopback() {
// 跳过IPV6
if ipNet.IP.To4() != nil {
ipv4 = ipNet.IP.String() // 192.168.1.1
return
}
}
}
err = fmt.Errorf("not found ip")
return
}
func NewRequestId() string {
return uuid.NewV4().String()
}
Go
1
https://gitee.com/scottq/go-framework.git
git@gitee.com:scottq/go-framework.git
scottq
go-framework
go-framework
v1.1.21

搜索帮助