utils.go 6.9 KB

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