|
|
@ -1,6 +1,9 @@
|
|
|
|
package hashid
|
|
|
|
package hashid
|
|
|
|
|
|
|
|
|
|
|
|
import "github.com/HFO4/cloudreve/pkg/conf"
|
|
|
|
import (
|
|
|
|
|
|
|
|
"errors"
|
|
|
|
|
|
|
|
"github.com/HFO4/cloudreve/pkg/conf"
|
|
|
|
|
|
|
|
)
|
|
|
|
import "github.com/speps/go-hashids"
|
|
|
|
import "github.com/speps/go-hashids"
|
|
|
|
|
|
|
|
|
|
|
|
// ID类型
|
|
|
|
// ID类型
|
|
|
@ -9,6 +12,10 @@ const (
|
|
|
|
UserID // 用户
|
|
|
|
UserID // 用户
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
var (
|
|
|
|
|
|
|
|
ErrTypeNotMatch = errors.New("ID类型不匹配")
|
|
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
// HashEncode 对给定数据计算HashID
|
|
|
|
// HashEncode 对给定数据计算HashID
|
|
|
|
func HashEncode(v []int) (string, error) {
|
|
|
|
func HashEncode(v []int) (string, error) {
|
|
|
|
hd := hashids.NewData()
|
|
|
|
hd := hashids.NewData()
|
|
|
@ -26,8 +33,32 @@ func HashEncode(v []int) (string, error) {
|
|
|
|
return id, nil
|
|
|
|
return id, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 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)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// HashID 计算数据库内主键对应的HashID
|
|
|
|
// HashID 计算数据库内主键对应的HashID
|
|
|
|
func HashID(id uint, t int) string {
|
|
|
|
func HashID(id uint, t int) string {
|
|
|
|
v, _ := HashEncode([]int{int(id), t})
|
|
|
|
v, _ := HashEncode([]int{int(id), t})
|
|
|
|
return v
|
|
|
|
return v
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// DecodeHashID 计算HashID对应的数据库ID
|
|
|
|
|
|
|
|
// TODO 测试
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
}
|
|
|
|