// 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
// Captcha拥有两个组件 type Captcha struct { Driver Driver Store Store }
//NewCaptcha creates a captcha instance from driver and store funcNewCaptcha(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) }