first commit
This commit is contained in:
25
pkg/hash/hash.go
Normal file
25
pkg/hash/hash.go
Normal file
@ -0,0 +1,25 @@
|
||||
package hash
|
||||
|
||||
var _ Hash = (*hash)(nil)
|
||||
|
||||
type Hash interface {
|
||||
i()
|
||||
|
||||
// hashids
|
||||
HashidsEncode(params []int) (string, error)
|
||||
HashidsDecode(hash string) ([]int, error)
|
||||
}
|
||||
|
||||
type hash struct {
|
||||
secret string
|
||||
length int
|
||||
}
|
||||
|
||||
func New(secret string, length int) Hash {
|
||||
return &hash{
|
||||
secret: secret,
|
||||
length: length,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *hash) i() {}
|
41
pkg/hash/hash_hashids.go
Normal file
41
pkg/hash/hash_hashids.go
Normal file
@ -0,0 +1,41 @@
|
||||
package hash
|
||||
|
||||
import (
|
||||
"github.com/speps/go-hashids"
|
||||
)
|
||||
|
||||
func (h *hash) HashidsEncode(params []int) (string, error) {
|
||||
hd := hashids.NewData()
|
||||
hd.Salt = h.secret
|
||||
hd.MinLength = h.length
|
||||
|
||||
hashID, err := hashids.NewWithData(hd)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
hashStr, err := hashID.Encode(params)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return hashStr, nil
|
||||
}
|
||||
|
||||
func (h *hash) HashidsDecode(hash string) ([]int, error) {
|
||||
hd := hashids.NewData()
|
||||
hd.Salt = h.secret
|
||||
hd.MinLength = h.length
|
||||
|
||||
hashID, err := hashids.NewWithData(hd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ids, err := hashID.DecodeWithError(hash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return ids, nil
|
||||
}
|
Reference in New Issue
Block a user