utils.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package common
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "fmt"
  6. "time"
  7. )
  8. import (
  9. "github.com/golang-jwt/jwt/v5"
  10. "github.com/spf13/cast"
  11. )
  12. var CstSh, _ = time.LoadLocation("Asia/Shanghai")
  13. const (
  14. LocateDateFormat = "2006-01-02"
  15. LocateTimeFormat = "2006-01-02 15:04:05"
  16. LocateMilliFormat = "2006-01-02 15:04:05.9999"
  17. )
  18. func Date() string {
  19. return time.Now().In(CstSh).Format(LocateDateFormat)
  20. }
  21. func Now() string {
  22. return time.Now().In(CstSh).Format(LocateTimeFormat)
  23. }
  24. func NowMilli() string {
  25. return time.Now().In(CstSh).Format(LocateMilliFormat)
  26. }
  27. func NewToken(userId uint, name string) (string, int64, error) {
  28. expire := time.Now().AddDate(0, 1, 0)
  29. hmacSampleSecret := []byte(BasicConfig.Jwt)
  30. token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
  31. "id": userId,
  32. "name": name,
  33. "exp": expire.Unix(),
  34. })
  35. str, err := token.SignedString(hmacSampleSecret)
  36. return str, expire.Unix(), err
  37. }
  38. func ParseToken(tokenString string) (uint, string, error) {
  39. token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
  40. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  41. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  42. }
  43. return []byte(BasicConfig.Jwt), nil
  44. })
  45. if err != nil {
  46. return 0, "", err
  47. }
  48. claims := token.Claims.(jwt.MapClaims)
  49. return cast.ToUint(claims["id"]), claims["name"].(string), nil
  50. }
  51. func MD5(v []byte) string {
  52. h := md5.New()
  53. h.Write(v)
  54. re := h.Sum(nil)
  55. return hex.EncodeToString(re)
  56. }