Golang (BEEGO) Verification Code Controller

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The core code is encapsulated by someone else's

The code is as follows:

/** * use) Register for routing * Beego. Router ("/yzm", &controllers. yzmcontroller{}, "Get:getyzm")//Verification code controller *beego. Router ("/yzm/judgeyzm", &controllers. yzmcontroller{}, "Post:judgeyzm")//Verification Code AJAX Verification * * 2) Usage *  */package controllersimport (crand" Crypto/rand "//" FMT "" Github.com/astaxie/beego "" github.com/ Astaxie/beego/session "" "Image" "Image/color" "image/png" "io" "Math/rand" "Net/http" "StrConv" "Time") var Globalsessions *session. Managerfunc init () {globalsessions, _ = session. Newmanager ("Memory", ' {"CookieName": "Gosessionid", "Enablesetcookie,omitempty": True, "gclifetime": 3600, " Maxlifetime ": 3600," secure ": false," Sessionidhashfunc ":" SHA1 "," Sessionidhashkey ":" "," Cookielifetime ": 3600," Providerconfig ":"} ') go Globalsessions.gc ()}type yzmcontroller struct {beego. controller}/** * Get Verification Code */func (this *yzmcontroller) Getyzm () {pic (this). Ctx.responsewriter, this. Ctx.request)}/** * Ajax Verification Code */func (this *yzmcontroller)Judgeyzm () {p: = this. GetString ("param") rs: = "Sorry, input" + p + "for error!" Sess: = Globalsessions.sessionstart (this. Ctx.responsewriter, this. ctx.request) if Sess. Get ("yzm") = = p {rs = "Y"///return y means correct}this. Ctx.writestring (RS)}const (stdwidth = 100stdHeight = 40maxSkew = 2) const (fontwidth = 5fontHeight = 8blackChar = 1) va R font = [][]byte{{//00, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0  0, 1, 1, 1, 0,},{/10, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1,},{//20, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1 , 1, 1, 1,},{//31, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1,  1, 1, 0,},{//41, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0,},{//51, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0,},{//60, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0,  0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0,},{//71, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0,},{//80, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0 , 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0,},{//90, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1,0, 0, 0, 0, 1,0, 0, 0, 0,, 1, 1, 1, 0,},}type Image struct {*image. Nrgbacolor *color. nrgbawidth int//a digit widthheight int//a digit heightdotsize int}func init () {rand. Seed (Int64 (time. Second))}func newimage (digits []byte, width, height int) *image {img: = new (image) R: = image. Rect (Img.width, Img.height, Stdwidth, Stdheight) img. Nrgba = image. Newnrgba (r) Img.color = &color. Nrgba{uint8 (Rand. INTN (129)), Uint8 (rand. INTN (129)), Uint8 (rand. INTN (129)), 0xff,}//Draw background (random circles of RAndom brightness) img.calculatesizes (width, height, len (digits)) Img.fillwithcircles (Ten, img.dotsize) Maxx: = width-(  img.width+img.dotsize) *len (digits)-Img.dotsizemaxy: = height-img.height-img.dotsize*2x: = Rnd (Img.dotsize*2, Maxx) y : = Rnd (img.dotsize*2, Maxy)//Draw Digits.for _, N: = range digits {img.drawdigit (font[n], x, y) x + = Img.width + img.dots ize}//Draw Strike-through Line.img.strikeThrough () return Img}func (img *image) writeto (w io. Writer) (Int64, error) {return 0, PNG. Encode (W, img)}func (img *image) calculatesizes (width, height, ncount int) {//Goal:fit all digits inside the Image.var b Order Intif width > Height {border = height/5} else {border = width/5}//Convert everything to floats for Calculati ONS.W: = Float64 (width-border*2)//268h: = Float64 (height-border*2)//48//FW takes into account 1-dot spacing Betwee N DIGITS.FW: = float64 (fontwidth) + 1//6FH: = Float64 (fontheight)//8nc: = Float64 (ncount)//7//Calculate the width of a single digit Taking into account only the//width of the IMAGE.NW: = W/nc//38//Calculate The height of a digit from this width.nh: = NW * FH/FW//51//Digit too high?if nh > H {//Fit digits based on height.nh = h//nh = 44NW = fw/fh * nh}//Calculat  E dot size.img.dotsize = Int (NH/FH)//Save Everything, making the actual width smaller by 1 dot-to-account//for spacing between digits.img.width = Int (NW) img.height = Int (NH)-Img.dotsize}func (img *image) fillwithcircles (n, Maxradius int) {color: = Img.colormaxx: = img. Bounds (). Max.xmaxy: = img. Bounds (). Max.yfor I: = 0; I < n; i++ {setrandombrightness (color, 255) R: = Rnd (1, Maxradius) img.drawcircle (color, Rnd (R, Maxx-r), Rnd (R, Maxy-r), R)}}func (img *image) drawhorizline (color color. Color, FromX, ToX, y int) {for x: = FromX; x <= ToX; Set (x, y, color)}}func (img *image) drawcircle (color color. Color, x, y, radius int) {f: = 1-radiusdfx: = 1dfy: =-2 * radiusxx: = 0yy: = radiusimg. Set (x, Y+radius, Color) img. Set (x, Y-radius, Color) img.drawhorizline (color, X-radius, X+radius, y) for xx < yy {if f >= 0 {yy--dfy + 2f + = dfy}xx++dfx + 2f + = DF Ximg.drawhorizline (color, x-xx, x+xx, y+yy) img.drawhorizline (color, x-xx, x+xx, y-yy) img.drawhorizline (color, x-yy, x+ YY, y+xx) img.drawhorizline (color, X-yy, X+yy, Y-XX)}}func (img *image) Strikethrough () {r: = 0maxx: = img. Bounds (). Max.xmaxy: = img. Bounds (). Max.yy: = Rnd (MAXY/3, MAXY-MAXY/3) for x: = 0; x < Maxx; X + = r {r = Rnd (1, img.dotsize/3) y + = rnd (-IMG.DOTSIZE/2, IMG.DOTSIZE/2) if y <= 0 | | y >= maxy {y = rnd (MAXY/3, Maxy -MAXY/3)}img.drawcircle (Img.color, x, Y, R)}}func (img *image) drawdigit (digit []byte, x, y int) {SKF: = rand. Float64 () * Float64 (Rnd (-maxskew, Maxskew)) xs: = float64 (x) Minr: = IMG.DOTSIZE/2//minumum RADIUSMAXR: = IMG.DOTSIZE/2 + IMG.DOTSIZE/4//maximum radiusy + rnd (-MINR, Minr) for yy: = 0; yy < Fontheight; yy++ {for XX: = 0; xx < fontwidth; xx++ {if digit[yy*fontwidth+xx]! = Blackchar {continue}//introduce Random variations.or: = Rnd (Minr, MAXR) Ox: = x + (XX * img.dotsize) + rnd (0, OR/2) Oy: = y + (yy * img.dotsize) + rnd (0, O R/2) img.drawcircle (Img.color, Ox, Oy, or)}xs + = SKFX = Int (xs)}}func setrandombrightness (c *color. Nrgba, Max Uint8) {minc: = min3 (C.R, C.G, c.b) Maxc: = Max3 (C.R, C.G, c.b) if MAXC > Max {return}n: = rand.  INTN (int (MAX-MAXC))-Int (minc) C.R = uint8 (int (C.R) + N) C.G = uint8 (int (C.G) + N) c.b = uint8 (int (C.B) + N)}func min3 (x, Y, Z uint8) (o uint8) {o = Xif y < o {o = y}if Z < o {o = Z}return}func max3 (x, y, z uint8) (o uint8) {o = xif y > o {o = y}if z > o {o = z}return}//rnd Returns a random number in range [From, To].func Rnd (from, to int) int {//printl N (to+1-from) return rand. INTN (To+1-from) + from}const (//Standard length of Uniuri string to achive ~95 bits of entropy. Stdlen = 16//Length of Uniurl string to achive ~119 bits of entropy, closest//to what can is losslessly converted to UUI DV4 (122 bits). Uuidlen = ()//standard characters allowed in UNIuri String.var stdchars = []byte ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")//New Returns a New random string of the standard length, consisting of//standard Characters.func New () string {return Newlenchars (Stdlen , stdchars)}//Newlen Returns a new random string of the provided length, consisting of//standard Characters.func Newlen ( length int) string {return Newlenchars (length, stdchars)}//Newlenchars Returns a new random string of the provided length , consisting//of the provided byte slice of allowed characters (maximum). Func newlenchars (length int, chars []byte) s Tring {b: = make ([]byte, length) R: = Yes ([]byte, length+ (LENGTH/4))//Storage for random Bytes.clen: = Byte (len (chars)) m AXRB: = Byte (chars)) I: = 0for {If _, err: = Io. Readfull (Crand. Reader, R); Err! = Nil {Panic ("Error reading from random Source:" + err.) Error ())}for _, c: = range R {if c >= maxrb {//Skip this number to avoid modulo bias.continue}b[i] = chars[c%clen]i++if i = = length {return string (b)}}}panic ("unreachable")}func pic (w http. Responsewriter, req *http. Request) {d: = make ([]byte, 4) S: = Newlen (4) SS: = "" D = []byte (s) for V: = range D {d[v]%= 10ss + = StrConv. Formatint (Int64 (D[v]),}w.header (). Set ("Content-type", "Image/png") Sess: = Globalsessions.sessionstart (W, req) defer Sess. Sessionrelease (W) sess. Delete ("Yzm") Sess. Set ("Yzm", ss)//fmt. Println ("-----------------------------------yzm:", Sess. Get ("Yzm")) NewImage (d, 100, 40). WriteTo (w)}func index (w http. Responsewriter, req *http. Request) {str: = "<meta charset=\" utf-8\ ">


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.