utils.go 5.9 KB

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