Beego下如何使用captcha生成验证码

Beego框架真的很贴心,默认有captcha这个验证码插件。在utils/captcha下面

使用方法

import(
    "github.com/astaxie/beego/cache"
    "github.com/astaxie/beego/utils/captcha"
)

var cpt *captcha.Captcha
func init() {
    store := cache.NewMemoryCache()
    cpt = captcha.NewWithFilter("/captcha/", store) //一定要写在构造函数里面,要不然第一次打开页面有可能是X
}

在模板里面写上   

<form action="/" method="post">
    {{create_captcha}}
    <input name="captcha" type="text">
</form>

就ok了,最贴心的是居然连onclick事件也已经做在了里面,方便。

还有判断也已经写好了,只要在post里面写上

if !cpt.VerifyReq(this.Ctx.Request) {
	//你的代码
}

默认的验证码是6位,200px宽,这个是可以自己设置的

cpt是一个结构体:

// Captcha struct
type Captcha struct {
    // beego cache store
    store cache.Cache

    // url prefix for captcha image
    URLPrefix string

    // specify captcha id input field name
    FieldIdName string
    // specify captcha result input field name
    FieldCaptchaName string

    // captcha image width and height
    StdWidth  int
    StdHeight int

    // captcha chars nums
    ChallengeNums int

    // captcha expiration seconds
    Expiration int64

    // cache key prefix
    CachePrefix string
}

 你看到暴露的这些接口了吗?图片的大小,字数都是可以调整的,字体、弯曲程度这些就不行。不过宽度也不是可以随意设置的,我测试的结果是宽度不能小于100,高度不能小于40.不知道是什么情况。

上代码:

func init() {
	store := cache.NewMemoryCache()
	cpt = captcha.NewWithFilter("/captcha/", store)
	cpt.ChallengeNums = 4
	cpt.StdWidth = 100
	cpt.StdHeight = 40
}

 

转载于:https://my.oschina.net/jinheking/blog/674707

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值