/* * @Descripttion: * @version: * @Author: Neo,Huang * @Date: 2020-10-20 14:01:47 * @LastEditors: Please set LastEditors * @LastEditTime: 2021-04-19 15:09:30 */ package utils import ( "bytes" "crypto/aes" "crypto/cipher" "encoding/hex" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "net/url" "os" "sort" "strconv" "strings" "time" "github.com/astaxie/beego" "github.com/astaxie/beego/config" "github.com/bitly/go-simplejson" ) // StringToInt string to int func StringToInt(itf interface{}) int { str, _ := itf.(string) i, _ := strconv.Atoi(str) return i } // IntToString int to string func IntToString(number int) string { return strconv.Itoa(number) } // StringToInt64 string to int64 func StringToInt64(itf interface{}) int64 { str, _ := itf.(string) i, _ := strconv.ParseInt(str, 10, 64) return i } // Int64ToString int64 to string func Int64ToString(number int64) string { return strconv.FormatInt(number, 10) } func JsonNumberToInt(itf interface{}) int { str := itf.(json.Number).String() return StringToInt(str) } // GetConf config func GetConf(key string, file string) string { iniconf, err := config.NewConfig("ini", file) if err != nil { fmt.Println(err.Error()) } return iniconf.String(key) } // ResponseHTTPJSON return json func ResponseHTTPJSON(w http.ResponseWriter, m map[string]interface{}) { str, _ := json.Marshal(m) w.Header().Set("Content-Length", IntToString(len(str))) w.Header().Set("Content-Type", "text/json") w.Write([]byte(str)) } // SendAndRecvHTTP send func SendAndRecvHTTP(method string, url string, body string) ([]byte, error) { client := &http.Client{} req, err1 := http.NewRequest(method, url, strings.NewReader(body)) if err1 != nil { return nil, err1 } req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Length", IntToString(len(body))) req.Header.Set("Connection", "close") resp, err2 := client.Do(req) if err2 != nil { return nil, err2 } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) } // 日志输出 func SetEventLog(strLog string, strFile string) { // 创建日志文件 filepath := fmt.Sprintf("/alidata/log/order/%s-%s.log", strFile, time.Now().Format("2006-01-02")) file, err := os.OpenFile(filepath, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) if err != nil { log.Println("create log file failed! err:", err) } defer file.Close() //获取当前程序执行的绝对路径 _, err = file.WriteString(strLog + "\n") if err != nil { log.Println("write string err:", err) } } // 应答 - 无签名 func ResponseUnsign(w http.ResponseWriter, m map[string]string) { str, _ := json.Marshal(m) w.Header().Set("Content-Length", IntToString(len(str))) w.Header().Set("Content-Type", "text/plain") w.Write([]byte(str)) } // http请求 - json参数 func RequestHttpJson(method string, url string, body string) ([]byte, error) { client := &http.Client{} req, err1 := http.NewRequest(method, url, strings.NewReader(body)) if err1 != nil { return nil, err1 } req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Length", IntToString(len(body))) req.Header.Set("Connection", "close") resp, err2 := client.Do(req) if err2 != nil { return nil, err2 } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) } // http请求 - url加密参数 func RequestHttpEncoded(method string, url string, body string) ([]byte, error) { client := &http.Client{} req, err1 := http.NewRequest(method, url, strings.NewReader(body)) if err1 != nil { return nil, err1 } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Content-Length", IntToString(len(body))) req.Header.Set("Connection", "close") resp, err2 := client.Do(req) if err2 != nil { return nil, err2 } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) } // 序列化url参数 func UrlSerial(values url.Values) (r string) { keys := make([]string, 0, len(values)) for k := range values { keys = append(keys, k) } sort.Strings(keys) for _, v := range keys { if r != "" { r += "&" } r += v + "=" + values.Get(v) } return } // 获取游戏密钥 func GetGameKey() string { configFile := GetConfigFile() gameKey := GetConf("servers::gameKey", configFile) return gameKey } // 获取游戏服地址 func GetGameHost() string { configFile := GetConfigFile() host := GetConf("servers::game", configFile) return host } // 获取趣头条参数 func GetQttConf(channel string, key string) string { configFile := GetConfigFile() host := GetConf(fmt.Sprintf("qttgame%s::%s", channel, key), configFile) return host } // 获取配置参数 func GetKeyConf(key string, subKey string) string { configFile := GetConfigFile() host := GetConf(fmt.Sprintf("%s::%s", key, subKey), configFile) return host } // 项目 var project string func InitProject() { project = beego.AppConfig.String("project") } func GetProject() string { return project } // 配置文件 func GetConfigFile() string { project := GetProject() configFile := fmt.Sprintf("conf/%s/cfg.conf", project) if beego.AppConfig.String("runmode") == "test" { configFile = fmt.Sprintf("conf/%s/cfg_test.conf", project) } return configFile } // 获取配置文件目录 func GetConfigPath() string { project := GetProject() return fmt.Sprintf("conf/%s/", project) } func pKCS5Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } func pKCS5UnPadding(origData []byte) []byte { length := len(origData) // 去掉最后一个字节 unpadding 次 unpadding := int(origData[length-1]) return origData[:(length - unpadding)] } // AesEncrypt aes加密函数,返回加密后的结果长度是16的倍数 func AesEncrypt(origData, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } blockSize := block.BlockSize() origData = pKCS5Padding(origData, blockSize) // iv := make([]byte, aes.BlockSize) iv := []byte("0304050607080910") blockMode := cipher.NewCBCEncrypter(block, iv) crypted := make([]byte, len(origData)) blockMode.CryptBlocks(crypted, origData) return crypted, nil } // AesDecrypt aes解密函数,传入解密内容长度必须是16的倍数 func AesDecrypt(crypted, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } // iv := make([]byte, aes.BlockSize) iv := []byte("0304050607080910") blockMode := cipher.NewCBCDecrypter(block, iv) origData := make([]byte, len(crypted)) blockMode.CryptBlocks(origData, crypted) origData = pKCS5UnPadding(origData) return origData, nil } func EncodeData(ts string, data string, appKey string) string { key := Md5(appKey + ts) en, err := AesEncrypt([]byte(data), []byte(key)) if err != nil { return "" } return strings.ToUpper(hex.EncodeToString(en)) } func DecodeData(ts string, data string) (string, error) { l := len(data) if l == 0 || (l%16) != 0 { return "", fmt.Errorf("decrype data error") } redAppKey := GetKeyConf("servers", "redAppKey") key := Md5(redAppKey + ts) buf, err1 := hex.DecodeString(data) if err1 != nil { return "", err1 } de, err2 := AesDecrypt(buf, []byte(key)) if err2 != nil { return "", err2 } return string(de), nil } // 加载json配置文件 func LoadJsonFile(fileName string) *simplejson.Json { data, err := ioutil.ReadFile(fileName) if err != nil { fmt.Println("load readFile", fileName, "err:", err) return nil } j, err := simplejson.NewJson(data) if err != nil { fmt.Println("load unmarshal", fileName, "err:", err) return nil } return j }