-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_test.go
72 lines (59 loc) · 1.61 KB
/
example_test.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
package ginaksk_test
import (
"crypto/md5"
"encoding/base64"
"errors"
"fmt"
"net/http"
"github.com/antlinker/ginaksk"
"github.com/gin-gonic/gin"
)
type store map[string]string
var keyStore = store{"ak": "sk"}
// GetKeyFunc 返回aksk.KeyFunc
func GetKeyFunc() ginaksk.KeyFunc {
return func(ak string) string {
return keyStore[ak]
}
}
type logger struct{}
var testLogger = &logger{}
func (l *logger) Printf(format string, args ...interface{}) {
fmt.Printf(format, args...)
}
func handlError(c *gin.Context, err error) {
if err == nil {
return
}
var aErr *ginaksk.Error
if errors.As(err, &aErr) {
c.AbortWithStatusJSON(http.StatusUnauthorized, map[string]interface{}{
"err_code": 1,
"err_msg": err.Error(),
})
return
}
testLogger.Printf("aksk error: %s", err)
c.AbortWithStatusJSON(http.StatusInternalServerError, map[string]interface{}{
"err_code": -1,
"err_msg": err.Error(),
})
}
type base64Encoder struct {
enc *base64.Encoding
}
func (b64 *base64Encoder) EncodeToString(b []byte) string {
return b64.enc.EncodeToString(b)
}
func (b64 *base64Encoder) DecodeString(s string) (b []byte, err error) {
return b64.enc.DecodeString(s)
}
func Example_aksk() {
ginaksk.SetLogger(testLogger) // 可选
ginaksk.SetHash(md5.New) // 可选
ginaksk.SetEncoder(&base64Encoder{enc: base64.RawStdEncoding}) // 可选
e := gin.New()
// 验证请求签名, 并验证请求内容, 自定义错误处理
e.Use(ginaksk.Validate(GetKeyFunc(), false, handlError))
// ginaksk.SetHash(sha1.New) // [Bad!] 取消注释会触发panic
}