utils.go 5.6 KB

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