| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- package utils
- import (
- "crypto/md5"
- "fmt"
- "github.com/golang-jwt/jwt/v4"
- "newaterobot-process/config"
- "regexp"
- "strings"
- )
- const (
- SessionUserIdKey = "uid"
- SessionDepIdKey = "dep"
- )
- type ClaimsDep struct {
- ID int
- Username string
- Dep string
- jwt.StandardClaims
- }
- var jwtSecret []byte
- func SetJWTSecret() {
- jwtSecret = []byte(config.GlobalConfig.JWT.Secret)
- }
- func ParseTokenWithDep(token string) (*ClaimsDep, error) {
- tokenClaims, err := jwt.ParseWithClaims(token, &ClaimsDep{}, func(token *jwt.Token) (interface{}, error) {
- return jwtSecret, nil
- })
- if tokenClaims != nil {
- if claims, ok := tokenClaims.Claims.(*ClaimsDep); ok && tokenClaims.Valid {
- return claims, nil
- }
- }
- return nil, err
- }
- // MD5 字符串MD5加密
- func MD5(s string) string {
- data := []byte(s)
- has := md5.Sum(data)
- return fmt.Sprintf("%x", has)
- }
- // IsEmail 验证邮箱格式
- func IsEmail(email string) bool {
- 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}$`
- reg := regexp.MustCompile(pattern)
- return reg.MatchString(email)
- }
- // IsMobile 验证手机号格式
- func IsMobile(mobile string) bool {
- pattern := `^1[3-9]\d{9}$`
- reg := regexp.MustCompile(pattern)
- return reg.MatchString(mobile)
- }
- // RemoveSpaces 去除字符串中的空格
- func RemoveSpaces(s string) string {
- return strings.ReplaceAll(s, " ", "")
- }
- // Substr 字符串截取
- func Substr(s string, start, length int) string {
- runes := []rune(s)
- total := len(runes)
- if start >= total {
- return ""
- }
- end := start + length
- if end > total {
- end = total
- }
- return string(runes[start:end])
- }
- func SplitAndFetch(s, sep string, index int) string {
- arr := strings.Split(s, sep)
- if index >= len(arr) {
- return ""
- }
- return arr[index]
- }
|