Cloudreve/pkg/hashid/hash.go

69 lines
1.3 KiB
Go
Raw Normal View History

2020-01-26 00:07:05 -05:00
package hashid
2020-01-26 01:57:07 -05:00
import (
"errors"
"github.com/HFO4/cloudreve/pkg/conf"
)
2020-01-26 00:07:05 -05:00
import "github.com/speps/go-hashids"
// ID类型
const (
ShareID = iota // 分享
UserID // 用户
FileID // 文件ID
FolderID // 目录ID
2020-02-11 22:38:04 -05:00
TagID // 标签ID
2020-02-18 00:45:59 -05:00
PolicyID // 存储策略ID
2020-01-26 00:07:05 -05:00
)
2020-01-26 01:57:07 -05:00
var (
2020-02-18 00:45:59 -05:00
// ErrTypeNotMatch ID类型不匹配
2020-01-26 01:57:07 -05:00
ErrTypeNotMatch = errors.New("ID类型不匹配")
)
2020-01-26 00:07:05 -05:00
// HashEncode 对给定数据计算HashID
func HashEncode(v []int) (string, error) {
hd := hashids.NewData()
hd.Salt = conf.SystemConfig.HashIDSalt
h, err := hashids.NewWithData(hd)
if err != nil {
return "", err
}
id, err := h.Encode(v)
if err != nil {
return "", err
}
return id, nil
}
2020-01-26 01:57:07 -05:00
// HashDecode 对给定数据计算原始数据
func HashDecode(raw string) ([]int, error) {
hd := hashids.NewData()
hd.Salt = conf.SystemConfig.HashIDSalt
h, err := hashids.NewWithData(hd)
if err != nil {
return []int{}, err
}
return h.DecodeWithError(raw)
}
2020-01-26 00:07:05 -05:00
// HashID 计算数据库内主键对应的HashID
func HashID(id uint, t int) string {
v, _ := HashEncode([]int{int(id), t})
return v
}
2020-01-26 01:57:07 -05:00
// DecodeHashID 计算HashID对应的数据库ID
func DecodeHashID(id string, t int) (uint, error) {
v, _ := HashDecode(id)
if len(v) != 2 || v[1] != t {
return 0, ErrTypeNotMatch
}
return uint(v[0]), nil
}