util.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/astaxie/beego"
  16. "github.com/astaxie/beego/config"
  17. )
  18. type RTLogStruct struct {
  19. ActionName string `json:"ty,omitempty"`
  20. Date string `json:"date,omitempty"`
  21. Event string `json:"cnt,omitempty"`
  22. }
  23. type RespondData struct {
  24. Code int `json:"Code,omitempty"`
  25. Message string `json:"Message,omitempty"`
  26. }
  27. func GetCurrentDirectory() string {
  28. file, err := exec.LookPath(os.Args[0])
  29. if err != nil {
  30. return ""
  31. }
  32. path, err := filepath.Abs(file)
  33. if err != nil {
  34. return ""
  35. }
  36. i := strings.LastIndex(path, "/")
  37. if i < 0 {
  38. i = strings.LastIndex(path, "\\")
  39. }
  40. if i < 0 {
  41. return ""
  42. }
  43. return string(path[0 : i+1])
  44. }
  45. // StringToInt string to int
  46. func StringToInt(itf interface{}) int {
  47. str, _ := itf.(string)
  48. i, _ := strconv.Atoi(str)
  49. return i
  50. }
  51. func StringToInt64(itf interface{}) int64 {
  52. str, _ := itf.(string)
  53. i, _ := strconv.ParseInt(str, 10, 64)
  54. return i
  55. }
  56. func StringToFloat(itf interface{}) float64 {
  57. str, _ := itf.(string)
  58. i, _ := strconv.ParseFloat(str, 64)
  59. return i
  60. }
  61. // IntToString int to string
  62. func IntToString(number int) string {
  63. return strconv.Itoa(number)
  64. }
  65. func Int64ToString(number int64) string {
  66. return fmt.Sprintf("%d", number)
  67. }
  68. // 项目
  69. var project string
  70. func InitProject() {
  71. project = beego.AppConfig.String("project")
  72. }
  73. func GetProject() string {
  74. return project
  75. }
  76. // 配置文件
  77. func GetConfigFile() string {
  78. project := GetProject()
  79. configFile := fmt.Sprintf("conf/%s/cfg.conf", project)
  80. if beego.AppConfig.String("runmode") == "test" {
  81. configFile = fmt.Sprintf("conf/%s/cfg_test.conf", project)
  82. }
  83. return configFile
  84. }
  85. // GetConf config
  86. func GetConf(key string, file string) string {
  87. iniconf, err := config.NewConfig("ini", file)
  88. if err != nil {
  89. fmt.Println(err.Error())
  90. }
  91. return iniconf.String(key)
  92. }
  93. // 获取配置参数
  94. func GetKeyConf(key string, subKey string) string {
  95. configFile := GetConfigFile()
  96. host := GetConf(fmt.Sprintf("%s::%s", key, subKey), configFile)
  97. return host
  98. }
  99. // 获取天开始时间
  100. func GetTimeDayStartTime(ti int) int {
  101. if ti == 0 {
  102. ti = int(time.Now().Unix())
  103. }
  104. str := time.Unix(int64(ti), 0).Format("2006-01-02") + " 00:00:00"
  105. loc, _ := time.LoadLocation("Local")
  106. theTime, err := time.ParseInLocation("2006-01-02 15:04:05", str, loc)
  107. if err == nil {
  108. return int(theTime.Unix())
  109. } else {
  110. return 0
  111. }
  112. }
  113. // 获取时间间隔天数
  114. func GetDiffDays(t1 int, t2 int) int {
  115. st1 := GetTimeDayStartTime(t1)
  116. st2 := GetTimeDayStartTime(t2)
  117. secs := 0
  118. if st2 > st1 {
  119. secs = st2 - st1
  120. } else {
  121. secs = st1 - st2
  122. }
  123. return secs / 86400
  124. }
  125. func IsSameDay(t1 int, t2 int) bool {
  126. deltaDays := GetDiffDays(t1, t2)
  127. if deltaDays == 0 {
  128. return true
  129. }
  130. return false
  131. }
  132. func GetTime(timeStr string) int {
  133. loc, _ := time.LoadLocation("Local")
  134. theTime, err := time.ParseInLocation("2006-01-02 15:04:05", timeStr, loc)
  135. if err == nil {
  136. return int(theTime.Unix())
  137. } else {
  138. return 0
  139. }
  140. }
  141. func GetTime64(timeStr string) int64 {
  142. loc, _ := time.LoadLocation("Local")
  143. theTime, err := time.ParseInLocation("2006-01-02 15:04:05", timeStr, loc)
  144. if err == nil {
  145. return theTime.Unix()
  146. }
  147. return int64(0)
  148. }
  149. // SendAndRecvHTTP send
  150. func SendAndRecvHTTP(method string, url string, body string) ([]byte, error) {
  151. client := &http.Client{}
  152. req, err1 := http.NewRequest(method, url, strings.NewReader(body))
  153. if err1 != nil {
  154. return nil, err1
  155. }
  156. req.Header.Set("Content-Type", "application/json")
  157. req.Header.Set("Content-Length", IntToString(len(body)))
  158. req.Header.Set("Connection", "close")
  159. resp, err2 := client.Do(req)
  160. if err2 != nil {
  161. return nil, err2
  162. }
  163. defer resp.Body.Close()
  164. return ioutil.ReadAll(resp.Body)
  165. }
  166. // 写埋点日志
  167. func WriteLog(action *RTLogStruct) {
  168. path := GetKeyConf("events", "path")
  169. if err := os.MkdirAll(path, 0766); err != nil {
  170. log.Printf("创建路径 [%s] 失败", path)
  171. return
  172. }
  173. fileName := fmt.Sprintf("%s/%s-%s.log", GetKeyConf("events", "path"), action.ActionName, action.Date)
  174. file, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
  175. if err != nil {
  176. log.Printf("打开文件 %s 失败", fileName)
  177. return
  178. }
  179. defer file.Close()
  180. file.WriteString(action.Event + "\n")
  181. }
  182. // InSlice 判断字符串是否在 slice 中。
  183. func InSlice(items []string, item string) bool {
  184. for _, eachItem := range items {
  185. if eachItem == item {
  186. return true
  187. }
  188. }
  189. return false
  190. }
  191. // Strtomd5 md5
  192. func Strtomd5(s string) string {
  193. h := md5.New()
  194. h.Write([]byte(s))
  195. rs := hex.EncodeToString(h.Sum(nil))
  196. return rs
  197. }