github.com/mojocn/base64Captcha

暴露接口如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Driver captcha interface for captcha engine to to write staff
type Driver interface {
//DrawCaptcha draws binary item
DrawCaptcha(content string) (item Item, err error)
//GenerateIdQuestionAnswer creates rand id, content and answer
GenerateIdQuestionAnswer() (id, q, a string)
}

type Store interface {
// Set sets the digits for the captcha id.
Set(id string, value string)

// Get returns stored digits for the captcha id. Clear indicates
// whether the captcha must be deleted from the store.
Get(id string, clear bool) string

//Verify captcha's answer directly
Verify(id, answer string, clear bool) bool
}
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
package base64Captcha

import "strings"

// Captcha拥有两个组件
type Captcha struct {
Driver Driver
Store Store
}

//NewCaptcha creates a captcha instance from driver and store
func NewCaptcha(driver Driver, store Store) *Captcha {
return &Captcha{Driver: driver, Store: store}
}

//Generate generates a random id, base64 image string or an error if any
func (c *Captcha) Generate() (id, b64s string, err error) {
id, content, answer := c.Driver.GenerateIdQuestionAnswer()
item, err := c.Driver.DrawCaptcha(content)
if err != nil {
return "", "", err
}
c.Store.Set(id, answer)
b64s = item.EncodeB64string()
return
}

//Verify by a given id key and remove the captcha value in store,
//return boolean value.
//if you has multiple captcha instances which share a same store.
//You may want to call `store.Verify` method instead.
func (c *Captcha) Verify(id, answer string, clear bool) (match bool) {
vv := c.Store.Get(id, clear)
//fix issue for some redis key-value string value
vv = strings.TrimSpace(vv)
return vv == strings.TrimSpace(answer)
}