目前 chptcha 好像只可以生成纯数字的图像验证码,不过对于普通简单应用来说也足够了。captcha默认将store封装到内部,未提供对外操作的接口,因此使用自己显式生成的store,可以通过store自定义要生成的验证码。
package mainimport ("bytes""fmt""github.com/dchest/captcha""log""os"
)// Captcha 方便后期扩展
type Captcha struct{}// 单例
var captchaInstance *Captchafunc Instance() *Captcha {if captchaInstance == nil {captchaInstance = &Captcha{}}return captchaInstance
}// CreateImage 创建图片验证码
func (this *Captcha) CreateImage() string {length := captcha.DefaultLencaptchaId := captcha.NewLen(length)return captchaId
}// Reload 重载
func (this *Captcha) Reload(captchaId string) bool {return captcha.Reload(captchaId)
}// Verify 验证
func (this *Captcha) VerifyString(captchaId, val string) bool {return captcha.VerifyString(captchaId, val)
}func (this *Captcha) Verify(captchaId string, digits []byte) bool {return captcha.Verify(captchaId, digits)
}// GetImageByte 获取图片二进制流
func (this *Captcha) GetImageByte(captchaId string) []byte {var content bytes.Buffererr := captcha.WriteImage(&content, captchaId, captcha.StdWidth, captcha.StdHeight)if err != nil {log.Println(err)return nil}return content.Bytes()
}// WriteImageFile 写图片文件
func (this *Captcha) WriteImageFile(b []byte, file string) {f, err := os.OpenFile(file, os.O_CREATE | os.O_RDWR, os.ModePerm)defer f.Close()if err != nil {log.Println(err)}f.Write(b)
}func main() {// capt := Instance()// captId := capt.CreateImage()// capt.WriteImageFile(capt.GetImageByte(captId), "test.png")// captcha默认将store封装到内部,未提供对外操作的接口// 使用自己显式生成的store,可以通过store自定义要生成的图形验证码store := captcha.NewMemoryStore(captcha.CollectNum, captcha.Expiration)captcha.SetCustomStore(store)capt := Instance()captId := capt.CreateImage()b := []byte{6, 6, 6, 8, 8, 8}store.Set(captId, b)// store.Set(captId, captcha.RandomDigits(6))fmt.Println(store.Get(captId, false))capt.WriteImageFile(capt.GetImageByte(captId), "test.png")// vs := capt.VerifyString(captId, "666888")v := capt.Verify(captId, b)if v {fmt.Println("verify succeed")} else {fmt.Println("verify failed")}
}