util.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /*
  2. * @Descripttion:
  3. * @version:
  4. * @Author: Neo,Huang
  5. * @Date: 2020-10-20 14:01:47
  6. * @LastEditors: Please set LastEditors
  7. * @LastEditTime: 2021-04-19 15:09:30
  8. */
  9. package utils
  10. import (
  11. "bytes"
  12. "crypto/aes"
  13. "crypto/cipher"
  14. "encoding/hex"
  15. "encoding/json"
  16. "fmt"
  17. "io/ioutil"
  18. "log"
  19. "net/http"
  20. "net/url"
  21. "os"
  22. "sort"
  23. "strconv"
  24. "strings"
  25. "time"
  26. "github.com/astaxie/beego"
  27. "github.com/astaxie/beego/config"
  28. "github.com/bitly/go-simplejson"
  29. )
  30. // StringToInt string to int
  31. func StringToInt(itf interface{}) int {
  32. str, _ := itf.(string)
  33. i, _ := strconv.Atoi(str)
  34. return i
  35. }
  36. // IntToString int to string
  37. func IntToString(number int) string {
  38. return strconv.Itoa(number)
  39. }
  40. // StringToInt64 string to int64
  41. func StringToInt64(itf interface{}) int64 {
  42. str, _ := itf.(string)
  43. i, _ := strconv.ParseInt(str, 10, 64)
  44. return i
  45. }
  46. // Int64ToString int64 to string
  47. func Int64ToString(number int64) string {
  48. return strconv.FormatInt(number, 10)
  49. }
  50. func JsonNumberToInt(itf interface{}) int {
  51. str := itf.(json.Number).String()
  52. return StringToInt(str)
  53. }
  54. // GetConf config
  55. func GetConf(key string, file string) string {
  56. iniconf, err := config.NewConfig("ini", file)
  57. if err != nil {
  58. fmt.Println(err.Error())
  59. }
  60. return iniconf.String(key)
  61. }
  62. // ResponseHTTPJSON return json
  63. func ResponseHTTPJSON(w http.ResponseWriter, m map[string]interface{}) {
  64. str, _ := json.Marshal(m)
  65. w.Header().Set("Content-Length", IntToString(len(str)))
  66. w.Header().Set("Content-Type", "text/json")
  67. w.Write([]byte(str))
  68. }
  69. // SendAndRecvHTTP send
  70. func SendAndRecvHTTP(method string, url string, body string) ([]byte, error) {
  71. client := &http.Client{}
  72. req, err1 := http.NewRequest(method, url, strings.NewReader(body))
  73. if err1 != nil {
  74. return nil, err1
  75. }
  76. req.Header.Set("Content-Type", "application/json")
  77. req.Header.Set("Content-Length", IntToString(len(body)))
  78. req.Header.Set("Connection", "close")
  79. resp, err2 := client.Do(req)
  80. if err2 != nil {
  81. return nil, err2
  82. }
  83. defer resp.Body.Close()
  84. return ioutil.ReadAll(resp.Body)
  85. }
  86. // 日志输出
  87. func SetEventLog(strLog string, strFile string) {
  88. // 创建日志文件
  89. filepath := fmt.Sprintf("/alidata/log/order/%s-%s.log", strFile, time.Now().Format("2006-01-02"))
  90. file, err := os.OpenFile(filepath, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
  91. if err != nil {
  92. log.Println("create log file failed! err:", err)
  93. }
  94. defer file.Close()
  95. //获取当前程序执行的绝对路径
  96. _, err = file.WriteString(strLog + "\n")
  97. if err != nil {
  98. log.Println("write string err:", err)
  99. }
  100. }
  101. // 应答 - 无签名
  102. func ResponseUnsign(w http.ResponseWriter, m map[string]string) {
  103. str, _ := json.Marshal(m)
  104. w.Header().Set("Content-Length", IntToString(len(str)))
  105. w.Header().Set("Content-Type", "text/plain")
  106. w.Write([]byte(str))
  107. }
  108. // http请求 - json参数
  109. func RequestHttpJson(method string, url string, body string) ([]byte, error) {
  110. client := &http.Client{}
  111. req, err1 := http.NewRequest(method, url, strings.NewReader(body))
  112. if err1 != nil {
  113. return nil, err1
  114. }
  115. req.Header.Set("Content-Type", "application/json")
  116. req.Header.Set("Content-Length", IntToString(len(body)))
  117. req.Header.Set("Connection", "close")
  118. resp, err2 := client.Do(req)
  119. if err2 != nil {
  120. return nil, err2
  121. }
  122. defer resp.Body.Close()
  123. return ioutil.ReadAll(resp.Body)
  124. }
  125. // http请求 - url加密参数
  126. func RequestHttpEncoded(method string, url string, body string) ([]byte, error) {
  127. client := &http.Client{}
  128. req, err1 := http.NewRequest(method, url, strings.NewReader(body))
  129. if err1 != nil {
  130. return nil, err1
  131. }
  132. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  133. req.Header.Set("Content-Length", IntToString(len(body)))
  134. req.Header.Set("Connection", "close")
  135. resp, err2 := client.Do(req)
  136. if err2 != nil {
  137. return nil, err2
  138. }
  139. defer resp.Body.Close()
  140. return ioutil.ReadAll(resp.Body)
  141. }
  142. // 序列化url参数
  143. func UrlSerial(values url.Values) (r string) {
  144. keys := make([]string, 0, len(values))
  145. for k := range values {
  146. keys = append(keys, k)
  147. }
  148. sort.Strings(keys)
  149. for _, v := range keys {
  150. if r != "" {
  151. r += "&"
  152. }
  153. r += v + "=" + values.Get(v)
  154. }
  155. return
  156. }
  157. // 获取游戏密钥
  158. func GetGameKey() string {
  159. configFile := GetConfigFile()
  160. gameKey := GetConf("servers::gameKey", configFile)
  161. return gameKey
  162. }
  163. // 获取游戏服地址
  164. func GetGameHost() string {
  165. configFile := GetConfigFile()
  166. host := GetConf("servers::game", configFile)
  167. return host
  168. }
  169. // 获取趣头条参数
  170. func GetQttConf(channel string, key string) string {
  171. configFile := GetConfigFile()
  172. host := GetConf(fmt.Sprintf("qttgame%s::%s", channel, key), configFile)
  173. return host
  174. }
  175. // 获取配置参数
  176. func GetKeyConf(key string, subKey string) string {
  177. configFile := GetConfigFile()
  178. host := GetConf(fmt.Sprintf("%s::%s", key, subKey), configFile)
  179. return host
  180. }
  181. // 项目
  182. var project string
  183. func InitProject() {
  184. project = beego.AppConfig.String("project")
  185. }
  186. func GetProject() string {
  187. return project
  188. }
  189. // 配置文件
  190. func GetConfigFile() string {
  191. project := GetProject()
  192. configFile := fmt.Sprintf("conf/%s/cfg.conf", project)
  193. if beego.AppConfig.String("runmode") == "test" {
  194. configFile = fmt.Sprintf("conf/%s/cfg_test.conf", project)
  195. }
  196. return configFile
  197. }
  198. // 获取配置文件目录
  199. func GetConfigPath() string {
  200. project := GetProject()
  201. return fmt.Sprintf("conf/%s/", project)
  202. }
  203. func pKCS5Padding(ciphertext []byte, blockSize int) []byte {
  204. padding := blockSize - len(ciphertext)%blockSize
  205. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  206. return append(ciphertext, padtext...)
  207. }
  208. func pKCS5UnPadding(origData []byte) []byte {
  209. length := len(origData)
  210. // 去掉最后一个字节 unpadding 次
  211. unpadding := int(origData[length-1])
  212. return origData[:(length - unpadding)]
  213. }
  214. // AesEncrypt aes加密函数,返回加密后的结果长度是16的倍数
  215. func AesEncrypt(origData, key []byte) ([]byte, error) {
  216. block, err := aes.NewCipher(key)
  217. if err != nil {
  218. return nil, err
  219. }
  220. blockSize := block.BlockSize()
  221. origData = pKCS5Padding(origData, blockSize)
  222. // iv := make([]byte, aes.BlockSize)
  223. iv := []byte("0304050607080910")
  224. blockMode := cipher.NewCBCEncrypter(block, iv)
  225. crypted := make([]byte, len(origData))
  226. blockMode.CryptBlocks(crypted, origData)
  227. return crypted, nil
  228. }
  229. // AesDecrypt aes解密函数,传入解密内容长度必须是16的倍数
  230. func AesDecrypt(crypted, key []byte) ([]byte, error) {
  231. block, err := aes.NewCipher(key)
  232. if err != nil {
  233. return nil, err
  234. }
  235. // iv := make([]byte, aes.BlockSize)
  236. iv := []byte("0304050607080910")
  237. blockMode := cipher.NewCBCDecrypter(block, iv)
  238. origData := make([]byte, len(crypted))
  239. blockMode.CryptBlocks(origData, crypted)
  240. origData = pKCS5UnPadding(origData)
  241. return origData, nil
  242. }
  243. func EncodeData(ts string, data string, appKey string) string {
  244. key := Md5(appKey + ts)
  245. en, err := AesEncrypt([]byte(data), []byte(key))
  246. if err != nil {
  247. return ""
  248. }
  249. return strings.ToUpper(hex.EncodeToString(en))
  250. }
  251. func DecodeData(ts string, data string) (string, error) {
  252. l := len(data)
  253. if l == 0 || (l%16) != 0 {
  254. return "", fmt.Errorf("decrype data error")
  255. }
  256. redAppKey := GetKeyConf("servers", "redAppKey")
  257. key := Md5(redAppKey + ts)
  258. buf, err1 := hex.DecodeString(data)
  259. if err1 != nil {
  260. return "", err1
  261. }
  262. de, err2 := AesDecrypt(buf, []byte(key))
  263. if err2 != nil {
  264. return "", err2
  265. }
  266. return string(de), nil
  267. }
  268. // 加载json配置文件
  269. func LoadJsonFile(fileName string) *simplejson.Json {
  270. data, err := ioutil.ReadFile(fileName)
  271. if err != nil {
  272. fmt.Println("load readFile", fileName, "err:", err)
  273. return nil
  274. }
  275. j, err := simplejson.NewJson(data)
  276. if err != nil {
  277. fmt.Println("load unmarshal", fileName, "err:", err)
  278. return nil
  279. }
  280. return j
  281. }