utils.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package library
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gogf/gf/crypto/gmd5"
  6. "github.com/gogf/gf/database/gdb"
  7. "github.com/gogf/gf/encoding/gcharset"
  8. "github.com/gogf/gf/encoding/gjson"
  9. "github.com/gogf/gf/encoding/gurl"
  10. "github.com/gogf/gf/errors/gerror"
  11. "github.com/gogf/gf/frame/g"
  12. "github.com/gogf/gf/net/ghttp"
  13. "github.com/gogf/gf/os/gtime"
  14. "github.com/gogf/gf/text/gstr"
  15. "github.com/gogf/gf/util/gconv"
  16. "math/rand"
  17. "net"
  18. "os"
  19. "os/exec"
  20. "path/filepath"
  21. "strconv"
  22. "strings"
  23. "time"
  24. )
  25. //密码加密
  26. func EncryptPassword(password, salt string) string {
  27. return gmd5.MustEncryptString(gmd5.MustEncryptString(password) + gmd5.MustEncryptString(salt))
  28. }
  29. //时间戳转 yyyy-MM-dd HH:mm:ss
  30. func TimeStampToDateTime(timeStamp int64) string {
  31. tm := gtime.NewFromTimeStamp(timeStamp)
  32. return tm.Format("Y-m-d H:i:s")
  33. }
  34. //时间戳转 yyyy-MM-dd
  35. func TimeStampToDate(timeStamp int64) string {
  36. tm := gtime.NewFromTimeStamp(timeStamp)
  37. return tm.Format("Y-m-d")
  38. }
  39. //获取当前请求接口域名
  40. func GetDomain(r *ghttp.Request) (string, error) {
  41. pathInfo, err := gurl.ParseURL(r.GetUrl(), -1)
  42. if err != nil {
  43. g.Log().Error(err)
  44. err = gerror.New("解析附件路径失败")
  45. return "", err
  46. }
  47. return fmt.Sprintf("%s://%s:%s/", pathInfo["scheme"], pathInfo["host"], pathInfo["port"]), nil
  48. }
  49. // GetUserAgent 获取user-agent
  50. func GetUserAgent(ctx context.Context) string {
  51. return ghttp.RequestFromCtx(ctx).Header.Get("User-Agent")
  52. }
  53. //获取客户端IP
  54. func GetClientIp(r *ghttp.Request) string {
  55. ip := r.Header.Get("X-Forwarded-For")
  56. if ip == "" {
  57. ip = r.GetClientIp()
  58. }
  59. return ip
  60. }
  61. //服务端ip
  62. func GetLocalIP() (ip string, err error) {
  63. addrs, err := net.InterfaceAddrs()
  64. if err != nil {
  65. return
  66. }
  67. for _, addr := range addrs {
  68. ipAddr, ok := addr.(*net.IPNet)
  69. if !ok {
  70. continue
  71. }
  72. if ipAddr.IP.IsLoopback() {
  73. continue
  74. }
  75. if !ipAddr.IP.IsGlobalUnicast() {
  76. continue
  77. }
  78. return ipAddr.IP.String(), nil
  79. }
  80. return
  81. }
  82. //获取ip所属城市
  83. func GetCityByIp(ip string) string {
  84. if ip == "" {
  85. return ""
  86. }
  87. if ip == "[::1]" || ip == "127.0.0.1" {
  88. return "内网IP"
  89. }
  90. url := "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=" + ip
  91. bytes := g.Client().GetBytes(url)
  92. src := string(bytes)
  93. srcCharset := "GBK"
  94. tmp, _ := gcharset.ToUTF8(srcCharset, src)
  95. json, err := gjson.DecodeToJson(tmp)
  96. if err != nil {
  97. return ""
  98. }
  99. if json.GetInt("code") == 0 {
  100. city := fmt.Sprintf("%s %s", json.GetString("pro"), json.GetString("city"))
  101. return city
  102. } else {
  103. return ""
  104. }
  105. }
  106. //日期字符串转时间戳(秒)
  107. func StrToTimestamp(dateStr string) int64 {
  108. tm, err := gtime.StrToTime(dateStr)
  109. if err != nil {
  110. g.Log().Error(err)
  111. return 0
  112. }
  113. return tm.Timestamp()
  114. }
  115. // GetDbConfig get db config
  116. func GetDbConfig() (cfg *gdb.ConfigNode, err error) {
  117. cfg = g.DB().GetConfig()
  118. err = ParseDSN(cfg)
  119. return
  120. }
  121. // ParseDSN parses the DSN string to a Config
  122. func ParseDSN(cfg *gdb.ConfigNode) (err error) {
  123. defer func() {
  124. if r := recover(); r != nil {
  125. err = gerror.New(r.(string))
  126. }
  127. }()
  128. dsn := cfg.Link
  129. if dsn == "" {
  130. return
  131. }
  132. foundSlash := false
  133. // gfast:123456@tcp(192.168.0.212:3306)/gfast-v2
  134. for i := len(dsn) - 1; i >= 0; i-- {
  135. if dsn[i] == '/' {
  136. foundSlash = true
  137. var j, k int
  138. // left part is empty if i <= 0
  139. if i > 0 {
  140. // [username[:password]@][protocol[(address)]]
  141. // Find the last '@' in dsn[:i]
  142. for j = i; j >= 0; j-- {
  143. if dsn[j] == '@' {
  144. // username[:password]
  145. // Find the first ':' in dsn[:j]
  146. for k = 0; k < j; k++ {
  147. if dsn[k] == ':' {
  148. cfg.Pass = dsn[k+1 : j]
  149. cfg.User = dsn[:k]
  150. break
  151. }
  152. }
  153. break
  154. }
  155. }
  156. // gfast:123456@tcp(192.168.0.212:3306)/gfast-v2
  157. // [protocol[(address)]]
  158. // Find the first '(' in dsn[j+1:i]
  159. var h int
  160. for k = j + 1; k < i; k++ {
  161. if dsn[k] == '(' {
  162. // dsn[i-1] must be == ')' if an address is specified
  163. if dsn[i-1] != ')' {
  164. if strings.ContainsRune(dsn[k+1:i], ')') {
  165. panic("invalid DSN: did you forget to escape a param value?")
  166. }
  167. panic("invalid DSN: network address not terminated (missing closing brace)")
  168. }
  169. for h = k + 1; h < i-1; h++ {
  170. if dsn[h] == ':' {
  171. cfg.Host = dsn[k+1 : h]
  172. cfg.Port = dsn[h+1 : i-1]
  173. break
  174. }
  175. }
  176. break
  177. }
  178. }
  179. }
  180. for j = i + 1; j < len(dsn); j++ {
  181. if dsn[j] == '?' {
  182. cfg.Name = dsn[i+1 : j]
  183. break
  184. } else {
  185. cfg.Name = dsn[i+1:]
  186. }
  187. }
  188. break
  189. }
  190. }
  191. if !foundSlash && len(dsn) > 0 {
  192. panic("invalid DSN: missing the slash separating the database name")
  193. }
  194. return
  195. }
  196. //获取附件真实路径
  197. func GetRealFilesUrl(r *ghttp.Request, path string) (realPath string, err error) {
  198. if gstr.ContainsI(path, "http") {
  199. realPath = path
  200. return
  201. }
  202. realPath, err = GetDomain(r)
  203. if err != nil {
  204. return
  205. }
  206. realPath = realPath + path
  207. return
  208. }
  209. //获取附件相对路径
  210. func GetFilesPath(fileUrl string) (path string, err error) {
  211. upType := gstr.ToLower(g.Cfg().GetString("upload.type"))
  212. upPath := gstr.Trim(g.Cfg().GetString("upload.local.UpPath"), "/")
  213. if upType != "local" || (upType == "local" && !gstr.ContainsI(fileUrl, upPath)) {
  214. path = fileUrl
  215. return
  216. }
  217. pathInfo, err := gurl.ParseURL(fileUrl, 32)
  218. if err != nil {
  219. g.Log().Error(err)
  220. err = gerror.New("解析附件路径失败")
  221. return
  222. }
  223. pos := gstr.PosI(pathInfo["path"], upPath)
  224. if pos >= 0 {
  225. path = gstr.SubStr(pathInfo["path"], pos)
  226. }
  227. return
  228. }
  229. //货币转化为分
  230. func CurrencyLong(currency interface{}) int64 {
  231. strArr := gstr.Split(gconv.String(currency), ".")
  232. switch len(strArr) {
  233. case 1:
  234. return gconv.Int64(strArr[0]) * 100
  235. case 2:
  236. if len(strArr[1]) == 1 {
  237. strArr[1] += "0"
  238. } else if len(strArr[1]) > 2 {
  239. strArr[1] = gstr.SubStr(strArr[1], 0, 2)
  240. }
  241. return gconv.Int64(strArr[0])*100 + gconv.Int64(strArr[1])
  242. }
  243. return 0
  244. }
  245. func GetExcPath() string {
  246. file, _ := exec.LookPath(os.Args[0])
  247. // 获取包含可执行文件名称的路径
  248. path, _ := filepath.Abs(file)
  249. // 获取可执行文件所在目录
  250. index := strings.LastIndex(path, string(os.PathSeparator))
  251. ret := path[:index]
  252. return strings.Replace(ret, "\\", "/", -1)
  253. }
  254. //流水号
  255. func CreateLogSn(prefix string) string {
  256. rand.Seed(time.Now().UnixNano())
  257. return prefix + strings.Replace(time.Now().Format("20060102150405.000"), ".", "", -1) + strconv.Itoa(rand.Intn(899)+100)
  258. }
  259. //获取随机整数
  260. func RandInt(max int) int {
  261. rand.Seed(time.Now().UnixNano())
  262. return rand.Intn(max)
  263. }
  264. //获取今天的开始时间 0点
  265. //gtime.New(time.Now()).StartOfDay()
  266. //获取今天的结束时间 24点
  267. //gtime.New(time.Now()).EndOfDay()
  268. //日期范围查询
  269. //whereCondition.Set(dao.UserInfo.Columns.CreatedAt+" >=", gtime.New(req.Date).StartOfDay())
  270. //whereCondition.Set(dao.UserInfo.Columns.CreatedAt+" <=", gtime.New(req.Date).EndOfDay())