util.go 7.1 KB

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