initial commit
This commit is contained in:
45
pkg/hashids/hashids.go
Normal file
45
pkg/hashids/hashids.go
Normal file
@@ -0,0 +1,45 @@
|
||||
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
|
||||
}
|
||||
33
pkg/hashids/hashids_test.go
Normal file
33
pkg/hashids/hashids_test.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package hashids
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDecodeCode(t *testing.T) {
|
||||
//code := "p5qggj"
|
||||
//code := "37rx8m"
|
||||
//code := "37r9dn"
|
||||
code := "pz9vew"
|
||||
err := os.Setenv("HASH_SALT", "qtyq68eqeqwy")
|
||||
|
||||
res, err := DecodeCode(code)
|
||||
require.NoError(t, err)
|
||||
fmt.Println(res)
|
||||
}
|
||||
|
||||
func TestGenerateCode(t *testing.T) {
|
||||
var productHub, dasht int64 = 1, 2
|
||||
|
||||
err := os.Setenv("HASH_SALT", "qtyq68eqeqwy")
|
||||
require.NoError(t, err)
|
||||
|
||||
phub := GenerateCode(productHub)
|
||||
fmt.Println(phub)
|
||||
dashtID := GenerateCode(dasht)
|
||||
fmt.Println(dashtID)
|
||||
}
|
||||
Reference in New Issue
Block a user