bee go用base64Captcha生成base64的验证码
废话不多说 直接 上代码:
login.go
package controllers import ( "fmt" "strings" "github.com/astaxie/beego" "github.com/mojocn/base64Captcha" ) var store = base64Captcha.DefaultMemStore /* var store base64Captcha.Store func init() { store = base64Captcha.DefaultMemStore // base64Captcha.DefaultMemStore是默认的:10240 个 过期时间10分钟 // 也可以自己设定参数base64Captcha.NewMemoryStore(GCLimitNumber, Expiration } */ type LoginController struct { beego.Controller } func If(condition bool, trueVal, falseVal interface{}) interface{} { if condition { return trueVal } else { return falseVal } } ///获取验证码 func (c *LoginController) Captcha() { type CaptchaResult struct { Id string `json:"captchaId"` Base64Blob string `json:"img"` } /* driverString := base64Captcha.DriverString{ Height: 30, Width: 60, NoiseCount: 0, ShowLineOptions: 2 | 2, Length: 4, Source: "1234567890qwertyuioplkjhgfdsazxcvbnm", BgColor: &color.RGBA{ R: 3, G: 102, B: 214, A: 125, }, Fonts: []string{"wqy-microhei.ttc"}, } driver := driverString.ConvertFonts() */ driver := base64Captcha.DefaultDriverDigit captcha := base64Captcha.NewCaptcha(driver, store) id, b64s, err := captcha.Generate() if err != nil { fmt.Println(err) } detail := make(map[string]string, 2) detail["captchaId"] = id detail["img"] = b64s res := make(map[string]interface{}, 3) res["status"] = 0 res["msg"] = "" res["data"] = detail c.Data["json"] = res c.ServeJSON() } ///登陆 func (c *LoginController) Verify() { type CaptchaData struct { captchaid string verifycode string } var obj CaptchaData var msg = "验证码不正确" verify := false //json data //json.Unmarshal(c.Ctx.Input.RequestBody, &obj) obj.captchaid = strings.TrimSpace(c.GetString("captchaid")) obj.verifycode = strings.TrimSpace(c.GetString("verifycode")) if obj.verifycode == "" || obj.captchaid == "" { msg = "验证码不能为空" } else { verify = store.Verify(obj.captchaid, obj.verifycode, true) if verify { msg = "" } } fmt.Println(verify) res := make(map[string]interface{}, 3) res["status"] = If(msg == "", 0, -1) res["msg"] = msg c.Data["json"] = res c.ServeJSON() }
修改路由文件 router.go 测试所有verify 就用GET方便
beego.Router("v1/api/captcha", &controllers.LoginController{}, "GET:Captcha") beego.Router("v1/api/verify", &controllers.LoginController{}, "GET:Verify")
运行效果:
把img 通过http://tool.chinaz.com/tools/imgtobase/ 可以查看正正的验证码
windows技术爱好者