common.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "fmt"
  5. "github.com/golang-jwt/jwt/v4"
  6. "newaterobot-process/config"
  7. "regexp"
  8. "strings"
  9. )
  10. const (
  11. SessionUserIdKey = "uid"
  12. SessionDepIdKey = "dep"
  13. )
  14. type ClaimsDep struct {
  15. ID int
  16. Username string
  17. Dep string
  18. jwt.StandardClaims
  19. }
  20. var jwtSecret []byte
  21. func SetJWTSecret() {
  22. jwtSecret = []byte(config.GlobalConfig.JWT.Secret)
  23. }
  24. func ParseTokenWithDep(token string) (*ClaimsDep, error) {
  25. tokenClaims, err := jwt.ParseWithClaims(token, &ClaimsDep{}, func(token *jwt.Token) (interface{}, error) {
  26. return jwtSecret, nil
  27. })
  28. if tokenClaims != nil {
  29. if claims, ok := tokenClaims.Claims.(*ClaimsDep); ok && tokenClaims.Valid {
  30. return claims, nil
  31. }
  32. }
  33. return nil, err
  34. }
  35. // MD5 字符串MD5加密
  36. func MD5(s string) string {
  37. data := []byte(s)
  38. has := md5.Sum(data)
  39. return fmt.Sprintf("%x", has)
  40. }
  41. // IsEmail 验证邮箱格式
  42. func IsEmail(email string) bool {
  43. pattern := `^[0-9a-z][_.0-9a-z-]{0,31}@([0-9a-z][0-9a-z-]{0,30}[0-9a-z]\.){1,4}[a-z]{2,4}$`
  44. reg := regexp.MustCompile(pattern)
  45. return reg.MatchString(email)
  46. }
  47. // IsMobile 验证手机号格式
  48. func IsMobile(mobile string) bool {
  49. pattern := `^1[3-9]\d{9}$`
  50. reg := regexp.MustCompile(pattern)
  51. return reg.MatchString(mobile)
  52. }
  53. // RemoveSpaces 去除字符串中的空格
  54. func RemoveSpaces(s string) string {
  55. return strings.ReplaceAll(s, " ", "")
  56. }
  57. // Substr 字符串截取
  58. func Substr(s string, start, length int) string {
  59. runes := []rune(s)
  60. total := len(runes)
  61. if start >= total {
  62. return ""
  63. }
  64. end := start + length
  65. if end > total {
  66. end = total
  67. }
  68. return string(runes[start:end])
  69. }
  70. func SplitAndFetch(s, sep string, index int) string {
  71. arr := strings.Split(s, sep)
  72. if index >= len(arr) {
  73. return ""
  74. }
  75. return arr[index]
  76. }