Files
gfast/library/libUtils/utils.go
T
2022-03-05 13:20:09 +08:00

95 lines
2.1 KiB
Go

/*
* @desc:工具
* @company:云南奇讯科技有限公司
* @Author: yixiaohu
* @Date: 2022/3/4 22:16
*/
package libUtils
import (
"context"
"fmt"
"github.com/gogf/gf/v2/crypto/gmd5"
"github.com/gogf/gf/v2/encoding/gcharset"
"github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/encoding/gurl"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"net"
)
// EncryptPassword 密码加密
func EncryptPassword(password, salt string) string {
return gmd5.MustEncryptString(gmd5.MustEncryptString(password) + gmd5.MustEncryptString(salt))
}
// GetDomain 获取当前请求接口域名
func GetDomain(ctx context.Context) string {
r := g.RequestFromCtx(ctx)
pathInfo, err := gurl.ParseURL(r.GetUrl(), -1)
if err != nil {
g.Log().Error(ctx, err)
return ""
}
return fmt.Sprintf("%s://%s:%s/", pathInfo["scheme"], pathInfo["host"], pathInfo["port"])
}
// GetClientIp 获取客户端IP
func GetClientIp(ctx context.Context) string {
return g.RequestFromCtx(ctx).GetClientIp()
}
// GetUserAgent 获取user-agent
func GetUserAgent(ctx context.Context) string {
return ghttp.RequestFromCtx(ctx).Header.Get("User-Agent")
}
// GetLocalIP 服务端ip
func GetLocalIP() (ip string, err error) {
var addrs []net.Addr
addrs, err = net.InterfaceAddrs()
if err != nil {
return
}
for _, addr := range addrs {
ipAddr, ok := addr.(*net.IPNet)
if !ok {
continue
}
if ipAddr.IP.IsLoopback() {
continue
}
if !ipAddr.IP.IsGlobalUnicast() {
continue
}
return ipAddr.IP.String(), nil
}
return
}
// GetCityByIp 获取ip所属城市
func GetCityByIp(ip string) string {
if ip == "" {
return ""
}
if ip == "[::1]" || ip == "127.0.0.1" {
return "内网IP"
}
url := "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=" + ip
bytes := g.Client().GetBytes(context.TODO(), url)
src := string(bytes)
srcCharset := "GBK"
tmp, _ := gcharset.ToUTF8(srcCharset, src)
json, err := gjson.DecodeToJson(tmp)
if err != nil {
return ""
}
if json.Get("code").Int() == 0 {
city := fmt.Sprintf("%s %s", json.Get("pro").String(), json.Get("city").String())
return city
} else {
return ""
}
}