1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
package base
import (
"encoding/json"
"strings"
"github.com/golang/glog"
"github.com/speps/go-hashids"
"golang.org/x/xerrors"
)
var seed *hashids.HashID
func init() {
Init("golang-advanced-json")
}
func Init(salt string) {
idData := hashids.NewData()
idData.Salt = salt
var err error
seed, err = hashids.NewWithData(idData)
if err != nil {
glog.Fatalf("initialize hash id failed, %s", err)
}
}
type ID int64
func (i ID) MarshalText() (text []byte, err error) {
if i < 0 {
return nil, xerrors.Errorf("err: ID(%d) must greater than 0", i)
}
str, err := seed.EncodeInt64([]int64{int64(i)})
if err != nil {
return nil, err
}
return []byte(str), nil
}
func (i *ID) UnmarshalText(text []byte) error {
is, err := seed.DecodeInt64WithError(string(text))
if err != nil {
return xerrors.Errorf("unmarshal id failed, %w", err)
}
if len(is) != 1 {
return xerrors.Errorf("bad unmarshal id length, %d", len(is))
}
*i = ID(is[0])
return nil
}
func (i ID) MarshalJSON() ([]byte, error) {
text, err := i.MarshalText()
if err != nil {
return nil, err
}
return json.Marshal(string(text))
}
func (i *ID) UnmarshalJSON(data []byte) error {
var text string
err := json.Unmarshal(data, &text)
if err != nil {
return err
}
return i.UnmarshalText([]byte(text))
}
func ParseIDList(str string) ([]ID, error) {
items := strings.Split(str, ",")
ids := make([]ID, 0, len(items))
for _, item := range items {
id := new(ID)
err := id.UnmarshalText([]byte(item))
if err != nil {
continue
}
ids = append(ids, *id)
}
return ids, nil
}
func ParseInt64List(str string) ([]int64, error) {
ids, err := ParseIDList(str)
if err != nil {
return nil, err
}
int64s := make([]int64, 0, len(ids))
for _, id := range ids {
int64s = append(int64s, int64(id))
}
return int64s, nil
}
func FormatIDList(ids []ID) (string, error) {
items := make([]string, 0, len(ids))
for _, id := range ids {
item, err := id.MarshalJSON()
if err != nil {
continue
}
items = append(items, string(item))
}
return strings.Join(items, ","), nil
}
|