hashid.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package hashid
  2. import (
  3. "errors"
  4. "os"
  5. "github.com/speps/go-hashids"
  6. )
  7. // ID类型
  8. const (
  9. UserID = iota // 用户
  10. ProjectID
  11. RenderTaskID
  12. CustomID
  13. )
  14. var (
  15. // ErrTypeNotMatch ID类型不匹配
  16. ErrTypeNotMatch = errors.New("ID类型不匹配")
  17. )
  18. // HashEncode 对给定数据计算HashID
  19. func HashEncode(v []int) (string, error) {
  20. hd := hashids.NewData()
  21. hd.Salt = os.Getenv("HASH_ID_SALT") //conf.SystemConfig.HashIDSalt
  22. h, err := hashids.NewWithData(hd)
  23. if err != nil {
  24. return "", err
  25. }
  26. id, err := h.Encode(v)
  27. if err != nil {
  28. return "", err
  29. }
  30. return id, nil
  31. }
  32. // HashDecode 对给定数据计算原始数据
  33. func HashDecode(raw string) ([]int, error) {
  34. hd := hashids.NewData()
  35. hd.Salt = os.Getenv("HASH_ID_SALT") // conf.SystemConfig.HashIDSalt
  36. h, err := hashids.NewWithData(hd)
  37. if err != nil {
  38. return []int{}, err
  39. }
  40. return h.DecodeWithError(raw)
  41. }
  42. // HashID 计算数据库内主键对应的HashID
  43. func HashID(id uint, t int) string {
  44. v, _ := HashEncode([]int{int(id), t})
  45. return v
  46. }
  47. // DecodeHashID 计算HashID对应的数据库ID
  48. func DecodeHashID(id string, t int) (uint, error) {
  49. v, _ := HashDecode(id)
  50. if len(v) != 2 || v[1] != t {
  51. return 0, ErrTypeNotMatch
  52. }
  53. return uint(v[0]), nil
  54. }