-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
73 lines (63 loc) · 1.82 KB
/
service.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
/**
* @Time : 19/05/2020 9:38 AM
* @Author : solacowa@gmail.com
* @File : service
* @Software: GoLand
*/
package captcha
import (
"bytes"
"context"
"github.com/dchest/captcha"
"log"
)
type Middleware func(Service) Service
type Service interface {
// GenCaptchaId 获取图形验证码ID
GenCaptchaId(ctx context.Context) string
// VerifyCaptcha 验证图形验证码
VerifyCaptcha(ctx context.Context, captchaId, verify string) bool
// Image 生成图片
Image(ctx context.Context, captchaId string, w, h int) []byte
// Refresh 刷新验证码图片
Refresh(ctx context.Context, w, h int) (captchaId string, res []byte)
}
type service struct {
//logger log.Logger
store captcha.Store
traceId string
}
func (s *service) Refresh(ctx context.Context, w, h int) (captchaId string, res []byte) {
captchaId = s.GenCaptchaId(ctx)
res = s.Image(ctx, captchaId, w, h)
return
}
func (s *service) Image(ctx context.Context, captchaId string, w, h int) []byte {
//logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId))
var content bytes.Buffer
captcha.SetCustomStore(s.store)
err := captcha.WriteImage(&content, captchaId, w, h)
if err != nil {
log.Println("captcha", "WriteImage", "err", err.Error())
//_ = level.Error(logger).Log("captcha", "WriteImage", "err", err.Error())
return nil
}
return content.Bytes()
}
func (s *service) VerifyCaptcha(ctx context.Context, captchaId, verify string) bool {
captcha.SetCustomStore(s.store)
return captcha.VerifyString(captchaId, verify)
}
func (s *service) GenCaptchaId(ctx context.Context) string {
captcha.SetCustomStore(s.store)
captchaId := captcha.NewLen(6)
return captchaId
}
func New(store captcha.Store, traceId string) Service {
//logger = log.With(logger, "service", "kit-captcha")
return &service{
//logger: logger,
store: store,
traceId: traceId,
}
}