46 lines
755 B
Go
46 lines
755 B
Go
package hashids
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
"github.com/speps/go-hashids"
|
|
)
|
|
|
|
var hids *hashids.HashID
|
|
|
|
func GetHashids() *hashids.HashID {
|
|
if hids != nil {
|
|
return hids
|
|
}
|
|
|
|
hidsData := hashids.NewData()
|
|
hidsData.Alphabet = "abcdefghijklmnopqrstuvwxyz1234567890"
|
|
hidsData.Salt = os.Getenv("HASH_SALT")
|
|
|
|
hidsData.MinLength = 6
|
|
h, _ := hashids.NewWithData(hidsData)
|
|
|
|
return h
|
|
}
|
|
|
|
func GenerateCode(id int64) string {
|
|
numbers := make([]int, 1)
|
|
numbers[0] = int(id)
|
|
encoded, _ := GetHashids().Encode(numbers)
|
|
return encoded
|
|
}
|
|
|
|
func DecodeCode(code string) (int, error) {
|
|
decoded, err := GetHashids().DecodeWithError(code)
|
|
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if len(decoded) < 1 {
|
|
return 0, fmt.Errorf("invalid code")
|
|
}
|
|
|
|
return decoded[0], nil
|
|
}
|