utils.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /*
  2. * @description:工具函数
  3. * @Author: CP
  4. * @Date: 2020-09-03 10:08:52
  5. * @FilePath: \construction_management\web\utils\utils.go
  6. */
  7. package utils
  8. import (
  9. "errors"
  10. "fmt"
  11. "io/ioutil"
  12. "log"
  13. "net/http"
  14. "net/url"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/dgrijalva/jwt-go"
  19. "github.com/kataras/iris/v12"
  20. "github.com/spf13/viper"
  21. "go.mod/comm"
  22. "go.mod/conf"
  23. )
  24. // 发送短信
  25. func SendSMS() {
  26. }
  27. // 获得员工组
  28. func GetAccountGroup() map[int]string {
  29. groupDate := map[int]string{
  30. 1: "建设单位",
  31. 2: "监理单位",
  32. 3: "施工单位",
  33. 4: "设计单位",
  34. 5: "代建单位",
  35. 6: "跟踪审计",
  36. 8: "总包单位",
  37. 9: "分包单位",
  38. 7: "其他",
  39. }
  40. return groupDate
  41. }
  42. // 字符串转换MAP
  43. func StringToMap(str string, split string) map[string]string {
  44. entries := strings.Split(str, split)
  45. strMap := make(map[string]string)
  46. for _, e := range entries {
  47. parts := strings.Split(e, ":")
  48. if len(parts) <= 1 {
  49. strMap["error"] = strings.Replace(parts[0], " ", "", -1)
  50. } else {
  51. strMap[strings.Replace(parts[0], " ", "", -1)] = strings.Replace(parts[1], " ", "", -1)
  52. }
  53. }
  54. return strMap
  55. }
  56. // 获得项目ID
  57. func GetBackstageKey(ctx iris.Context, key string) (string, error) {
  58. //account := ctx.Values().Get("account").(*models.CmProjectAccount)
  59. // fmt.Println(account)
  60. value := ctx.Values().GetString(key)
  61. if value == "" {
  62. return "", errors.New("员工名称不存在")
  63. }
  64. return value, nil
  65. }
  66. // 获得项目ID
  67. func GetProjectId(ctx iris.Context) (int, error) {
  68. //account := ctx.Values().Get("account").(*models.CmProjectAccount)
  69. // fmt.Println(account)
  70. projectId, err := ctx.Values().GetInt("projectId")
  71. if err != nil {
  72. return 0, errors.New("项目不存在")
  73. }
  74. return projectId, nil
  75. }
  76. // 获得项目账号ID
  77. func GetProjectAccountId(ctx iris.Context) (int, error) {
  78. identityIdInt, err := ctx.Values().GetInt("accountId")
  79. if err != nil {
  80. return 0, errors.New("项目账号不存在")
  81. }
  82. return identityIdInt, nil
  83. }
  84. // 获得解密后的ID
  85. func GetDecryptId(id string) (int, error) {
  86. if id == "" {
  87. return 0, errors.New("ID 解析错误")
  88. }
  89. id, err := comm.AesDecrypt(id, conf.SignSecret)
  90. if err != nil {
  91. return 0, errors.New("ID 解析错误")
  92. }
  93. idInt, err := strconv.Atoi(id)
  94. if err != nil {
  95. return 0, errors.New("ID 转换错误")
  96. }
  97. return idInt, nil
  98. }
  99. // 金额转字符串 保留2位小数
  100. func PriceToStringFormat(price float64) string {
  101. // fmt.Println("price=========================")
  102. // fmt.Println(price)
  103. return fmt.Sprintf("%.2f", price)
  104. // return fmt.Sprintf("%g", price)
  105. }
  106. // 生成code
  107. func CreateRuleCode(code int64, count int64, len int) string {
  108. // fmt.Println("rule", rule, "counts", count)
  109. // egRule := strings.Split(rule.Eg, "-")
  110. // for _, value := range egRule {
  111. // if strings.Contains(value, "_") {
  112. // // fmt.Println("rule", rule.Code, count)
  113. // code := fmt.Printf("%0*d", rule.Code, count+1)
  114. // strings.Replace(rule.Eg, )
  115. // }
  116. // }
  117. // fmt.Println("egRule:", egRule)
  118. // return "123"
  119. // var newCode string
  120. if code == 0 {
  121. a := fmt.Sprintf("%0*d", len, count)
  122. return a
  123. } else {
  124. b := fmt.Sprintf("%0*d", len, count+code)
  125. return b
  126. }
  127. }
  128. // 对计量请求token
  129. func CreateJlToken(data jwt.MapClaims) (string, error) {
  130. var (
  131. tokenString string
  132. err error
  133. )
  134. token := jwt.NewWithClaims(jwt.SigningMethodHS256, data)
  135. if tokenString, err = token.SignedString([]byte(conf.JLSecretKey)); err != nil {
  136. return "", err
  137. }
  138. return tokenString, nil
  139. }
  140. // 验证并解析JWT
  141. func ValidateJwt(tokenStr string) (map[string]interface{}, error) {
  142. // 0.测试时使用
  143. // 在这里声明令牌的到期时间,我们将其保留为5分钟
  144. tokenString, _ := CreateJlToken(jwt.MapClaims{
  145. "data": map[string]string{"code": "P0401", "account": "linqiang-2", "newAccount": "linqiang-3"},
  146. "exp": time.Now().Add(24 * time.Hour).Unix(),
  147. })
  148. log.Println("JWT 5分钟过期-开发使用,=", tokenString)
  149. // 1.验证并解析JWT
  150. parseAuth, err := jwt.Parse(tokenStr, func(*jwt.Token) (interface{}, error) {
  151. return []byte(conf.JLSecretKey), nil
  152. })
  153. if err != nil {
  154. log.Println("JWT异常, error=", err)
  155. return nil, err
  156. }
  157. if !parseAuth.Valid {
  158. if ve, ok := err.(*jwt.ValidationError); ok {
  159. if ve.Errors&jwt.ValidationErrorMalformed != 0 {
  160. return nil, errors.New("无效签名")
  161. } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
  162. return nil, errors.New("过期签名")
  163. } else {
  164. return nil, errors.New("无效签名")
  165. }
  166. }
  167. return nil, errors.New("无效签名")
  168. }
  169. // 1-2.转换为map
  170. claims := parseAuth.Claims.(jwt.MapClaims)
  171. data, ok := claims["data"].(map[string]interface{})
  172. if !ok {
  173. return nil, errors.New("解析data失败")
  174. }
  175. // jlRequest := jlRequest{}
  176. // err = json.Unmarshal(claims, &jlRequest)
  177. // if err != nil {
  178. // log.Println("请求移除, error=", err)
  179. // return errors.New("解析数据错误")
  180. // }
  181. // if err := json.Unmarshal(tokData, &claims); err != nil {
  182. // return nil, err
  183. // }
  184. return data, nil
  185. }
  186. func GetEnvInfo(env string) string {
  187. viper.AutomaticEnv()
  188. return viper.GetString(env)
  189. }
  190. type jlRequest struct {
  191. Data map[string]interface{} `json:"data" `
  192. }
  193. func PullData(method string, authUrl string, tokenString string) ([]byte, error) {
  194. var (
  195. err error
  196. reqest *http.Request
  197. )
  198. client := &http.Client{}
  199. if method == "POST" || method == "post" {
  200. // 1.构建请求体
  201. data := url.Values{}
  202. data.Set("auth", tokenString)
  203. parameter := strings.NewReader(data.Encode())
  204. // 2.开始请求准备
  205. reqest, err = http.NewRequest(method, authUrl, parameter)
  206. reqest.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  207. } else if method == "GET" || method == "get" {
  208. reqest, err = http.NewRequest(method, authUrl, nil)
  209. reqest.Header.Add("Content-Type", "application/json; charset=utf-8")
  210. }
  211. if err != nil {
  212. log.Println("请求移除, error=", err)
  213. return nil, errors.New("网络出现问题")
  214. }
  215. // 3.发送请求
  216. response, err := client.Do(reqest)
  217. if err != nil {
  218. log.Println("请求移除, error=", err)
  219. return nil, errors.New("网络出现问题")
  220. }
  221. if response.StatusCode != 200 {
  222. return nil, errors.New("请求发送错误")
  223. }
  224. // 4.结构化返回数据
  225. body, _ := ioutil.ReadAll(response.Body)
  226. return body, nil
  227. // fmt.Println(string(body))
  228. // result := map[string]interface{}{}
  229. // err = json.Unmarshal(body, &result)
  230. // if err != nil {
  231. // log.Println("请求移除, error=", err)
  232. // return nil, errors.New("解析数据错误")
  233. // }
  234. // if result["code"].(float64) != 0 {
  235. // return nil, errors.New(fmt.Sprintf("%s", result["msg"]))
  236. // }
  237. // return result, nil
  238. }
  239. // // 获得项目ID
  240. // func GetProjectId(ctx iris.Context) (int, error) {
  241. // jwtInfo := ctx.Values().Get("jwt").(*jwt.Token)
  242. // project := jwtInfo.Claims.(jwt.MapClaims)["project"].(string)
  243. // projectId, err := comm.AesDecrypt(project, conf.CookieSecret)
  244. // if err != nil {
  245. // return 0, errors.New("项目不存在")
  246. // }
  247. // projectIdInt, err := strconv.Atoi(projectId)
  248. // if err != nil {
  249. // return 0, errors.New("项目不存在")
  250. // }
  251. // return projectIdInt, nil
  252. // }
  253. // // 获得项目账号ID
  254. // func GetProjectAccountId(ctx iris.Context) (int, error) {
  255. // jwtInfo := ctx.Values().Get("jwt").(*jwt.Token)
  256. // identity := jwtInfo.Claims.(jwt.MapClaims)["identity"].(string)
  257. // identityId, err := comm.AesDecrypt(identity, conf.CookieSecret)
  258. // if err != nil {
  259. // return 0, errors.New("项目账号不存在")
  260. // }
  261. // identityIdInt, err := strconv.Atoi(identityId)
  262. // if err != nil {
  263. // return 0, errors.New("项目账号不存在")
  264. // }
  265. // return identityIdInt, nil
  266. // }