-
Notifications
You must be signed in to change notification settings - Fork 0
/
basetype.go
102 lines (83 loc) · 2.03 KB
/
basetype.go
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
package do
import (
"encoding/json"
"fmt"
"strconv"
"golang.org/x/crypto/bcrypt"
)
type (
Entity[U any] struct {
Id U `json:"id"` // id
Name string `json:"name"` // 名称
}
TreeEntity[U any] struct {
Entity[U]
Childs []Entity[U] `json:"childs"` // 子元素
}
)
type (
Pager struct {
Page int `json:"page" form:"page"` // page No.
PageSize int `json:"pageSize" form:"pageSize"` // page size
}
PageResult[T any] struct {
Total int64 `json:"total"` // total
ListResult[T]
}
ListResult[T any] struct {
List []T `json:"list"` // list
}
)
type (
IdType[T any] struct {
Id T `json:"id" form:"id"` // id
}
IdsType[T any] struct {
Ids []T `json:"ids" form:"ids"` // ids
}
)
// Id to/from string when json encode/decode
type Id uint64
var (
_ json.Marshaler = (*Id)(nil)
_ json.Unmarshaler = (*Id)(nil)
)
func (id Id) MarshalJSON() ([]byte, error) {
s := strconv.FormatUint(uint64(id), 10)
s = strconv.Quote(s)
return StringToBytes(s), nil
}
func (id *Id) UnmarshalJSON(data []byte) error {
s := BytesToString(data)
s, err := strconv.Unquote(s)
if err != nil {
return fmt.Errorf("[id] data unquote failed: %v of %s", err, data)
}
if s == "" {
return nil
}
i, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return fmt.Errorf("[id] data parse uint failed: %v of %s", err, data)
}
*id = Id(i)
return nil
}
type Password string
// Encrypt 使用bcrypt算法将明文密码哈希得到hash字符串
// bcrypt算法在对同一个密码哈希多次会得出不同结果,极大的保证了用户密码的安全
func (p Password) Encrypt() (pp string, err error) {
r, err := bcrypt.GenerateFromPassword([]byte(p), bcrypt.DefaultCost)
if err != nil {
return
}
return string(r), nil
}
// Compare 使用bcrypt算法判断密码是否与传入hash值匹配
func (p Password) Compare(hash string) error {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(p))
}
// Password 实现String方法,打印时自动替换为*
func (p Password) String() string {
return "*"
}