utils.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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) (map[string]interface{}, error) {
  136. // 0.测试时使用
  137. // 在这里声明令牌的到期时间,我们将其保留为5分钟
  138. tokenString, _ := CreateJlToken(jwt.MapClaims{
  139. "data": map[string]string{"code": "QL3D3", "account": "lanjianrong"},
  140. "exp": time.Now().Add(24 * time.Hour).Unix(),
  141. })
  142. log.Println("JWT 5分钟过期-开发使用,=", tokenString)
  143. // 1.验证并解析JWT
  144. parseAuth, err := jwt.Parse(tokenStr, func(*jwt.Token) (interface{}, error) {
  145. return []byte(conf.JLSecretKey), nil
  146. })
  147. if err != nil {
  148. log.Println("JWT异常, error=", err)
  149. return nil, err
  150. }
  151. if !parseAuth.Valid {
  152. if ve, ok := err.(*jwt.ValidationError); ok {
  153. if ve.Errors&jwt.ValidationErrorMalformed != 0 {
  154. return nil, errors.New("无效签名")
  155. } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
  156. return nil, errors.New("过期签名")
  157. } else {
  158. return nil, errors.New("无效签名")
  159. }
  160. }
  161. return nil, errors.New("无效签名")
  162. }
  163. // 1-2.转换为map
  164. claims := parseAuth.Claims.(jwt.MapClaims)
  165. data, ok := claims["data"].(map[string]interface{})
  166. if !ok {
  167. }
  168. // jlRequest := jlRequest{}
  169. // err = json.Unmarshal(claims, &jlRequest)
  170. // if err != nil {
  171. // log.Println("请求移除, error=", err)
  172. // return errors.New("解析数据错误")
  173. // }
  174. // if err := json.Unmarshal(tokData, &claims); err != nil {
  175. // return nil, err
  176. // }
  177. return data, nil
  178. }
  179. type jlRequest struct {
  180. Data map[string]interface{} `json:"data" `
  181. }
  182. func PullData(method string, authUrl string, tokenString string) ([]byte, error) {
  183. var (
  184. err error
  185. reqest *http.Request
  186. )
  187. client := &http.Client{}
  188. if method == "POST" || method == "post" {
  189. // 1.构建请求体
  190. data := url.Values{}
  191. data.Set("auth", tokenString)
  192. parameter := strings.NewReader(data.Encode())
  193. // 2.开始请求准备
  194. reqest, err = http.NewRequest(method, authUrl, parameter)
  195. reqest.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  196. } else if method == "GET" || method == "get" {
  197. reqest, err = http.NewRequest(method, authUrl, nil)
  198. reqest.Header.Add("Content-Type", "application/json; charset=utf-8")
  199. }
  200. if err != nil {
  201. log.Println("请求移除, error=", err)
  202. return nil, errors.New("网络出现问题")
  203. }
  204. // 3.发送请求
  205. response, err := client.Do(reqest)
  206. if err != nil {
  207. log.Println("请求移除, error=", err)
  208. return nil, errors.New("网络出现问题")
  209. }
  210. if response.StatusCode != 200 {
  211. return nil, errors.New("请求发送错误")
  212. }
  213. // 4.结构化返回数据
  214. body, _ := ioutil.ReadAll(response.Body)
  215. return body, nil
  216. // fmt.Println(string(body))
  217. // result := map[string]interface{}{}
  218. // err = json.Unmarshal(body, &result)
  219. // if err != nil {
  220. // log.Println("请求移除, error=", err)
  221. // return nil, errors.New("解析数据错误")
  222. // }
  223. // if result["code"].(float64) != 0 {
  224. // return nil, errors.New(fmt.Sprintf("%s", result["msg"]))
  225. // }
  226. // return result, nil
  227. }
  228. // // 获得项目ID
  229. // func GetProjectId(ctx iris.Context) (int, error) {
  230. // jwtInfo := ctx.Values().Get("jwt").(*jwt.Token)
  231. // project := jwtInfo.Claims.(jwt.MapClaims)["project"].(string)
  232. // projectId, err := comm.AesDecrypt(project, conf.CookieSecret)
  233. // if err != nil {
  234. // return 0, errors.New("项目不存在")
  235. // }
  236. // projectIdInt, err := strconv.Atoi(projectId)
  237. // if err != nil {
  238. // return 0, errors.New("项目不存在")
  239. // }
  240. // return projectIdInt, nil
  241. // }
  242. // // 获得项目账号ID
  243. // func GetProjectAccountId(ctx iris.Context) (int, error) {
  244. // jwtInfo := ctx.Values().Get("jwt").(*jwt.Token)
  245. // identity := jwtInfo.Claims.(jwt.MapClaims)["identity"].(string)
  246. // identityId, err := comm.AesDecrypt(identity, conf.CookieSecret)
  247. // if err != nil {
  248. // return 0, errors.New("项目账号不存在")
  249. // }
  250. // identityIdInt, err := strconv.Atoi(identityId)
  251. // if err != nil {
  252. // return 0, errors.New("项目账号不存在")
  253. // }
  254. // return identityIdInt, nil
  255. // }