Golang Image Verification Code

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

Why Base64 Pictures for RESTful services

  Data URIs 支持大部分浏览器,IE8之后也支持.  小图片使用base64响应对于RESTful服务来说更便捷

Godoc Documentation

Online demo Playground Powered by Vuejs+elementui+axios









WAV file

Installing the Golang Package

go get -u github.com/mojocn/base64Captcha

For Chinese mainland Gopher go get golang.org/x/image failure Solution:

    mkdir -p $GOPATH/src/golang.org/x    cd $GOPATH/src/golang.org/x    git clone https://github.com/golang/image.git

Create an image verification code

Import "Github.com/mojocn/base64captcha" func democodecaptchacreate () {//config struct for digits//digital Verification code configuration VAR c ONFIGD = base64captcha.configdigit{height:80, width:240, maxskew:0.7, Dotcount        : Captchalen:5,}//config struct for audio//sound Verification code configuration var Configa = base64captcha.configaudio{ Captchalen:6, Language: "zh",}//config struct for Character//character, formula, CAPTCHA configuration var CONFIGC = base 64captcha.configcharacter{height:60, width:240,//const captchamodenumber        : Numbers, Captchamodealphabet: Letters, captchamodearithmetic: Arithmetic, Captchamodenumberalphabet: mixed digital letters.        Mode:base64Captcha.CaptchaModeNumber, ComplexOfNoiseText:base64Captcha.CaptchaComplexLower,         ComplexOfNoiseDot:base64Captcha.CaptchaComplexLower, Isshowhollowline:false, Isshownoisedot:false, Isshownoisetext:false, IsshowslimeLine:false, Isshowsineline:false, Captchalen:6,}//Create a sound verification code//generatecaptcha first    The parameter is an empty string, and the package automatically generates random UIID on the server with a random seed. Idkeya, CapA: = Base64captcha.generatecaptcha ("", Configa)//base64 encoded Base64stringa: = Base64captcha.captchawriteto    Base64encoding (CapA)//Create character formula verification code.    Generatecaptcha The first parameter is an empty string, the package automatically generates random UIID on the server with a random seed. IDKEYC, CapC: = Base64captcha.generatecaptcha ("", CONFIGC)//base64 encoded BASE64STRINGC: = Base64captcha.captchawriteto    Base64encoding (CapC)//Create a digital verification code.    Generatecaptcha The first parameter is an empty string, the package automatically generates random UIID on the server with a random seed. Idkeyd, CapD: = Base64captcha.generatecaptcha ("", ConfigD)//base64 encoded BASE64STRINGD: = Base64captcha.captchawriteto Base64encoding (CapD) fmt. Println (Idkeya, Base64stringa, "\ n") fmt. Println (IDKEYC, BASE64STRINGC, "\ n") fmt. Println (Idkeyd, Base64stringd, "\ n")}

Verifying the Image Verification code

import "github.com/mojocn/base64Captcha"func verfiyCaptcha(idkey,verifyValue string){    verifyResult := base64Captcha.VerifyCaptcha(idkey, verifyValue)    if verifyResult {        //success    } else {        //fail    }}

Using Golang to build API services

Example of HTTP server that uses the captcha package.package mainimport ("Encoding/json" "FMT" "github.com/mo              Jocn/base64captcha "" "Log" "Net/http")//configjsonbody JSON request Body.type configjsonbody struct {Id String Captchatype string Verifyvalue string Configaudio base64captcha.configaudio Configchara Cter base64captcha.configcharacter configdigit base64captcha.configdigit}//base64captcha create http Handlerfunc g Eneratecaptchahandler (w http. Responsewriter, R *http. Request) {//parse requests parameters//Receive client to send the requested parameter decoder: = JSON. Newdecoder (R.body) var postparameters configjsonbody err: = decoder. Decode (&postparameters) if err! = Nil {log.     PRINTLN (ERR)} defer r.body.close ()//create base64 encoding CAPTCHA//Create Base64 image verification code var config interface{}      Switch Postparameters.captchatype {case ' audio ': config = postparameters.configaudio case ' character ':  Config = postparameters.configcharacter default:config = postparameters.configdigit}//generatecaptcha    The first parameter is an empty string, and the package automatically generates random UIID on the server with a random seed. Captchaid, Digitcap: = Base64captcha.generatecaptcha (postparameters.id, config) base64png: = Base64captcha.captchawritetobase64encoding (DIGITCAP)//or You can does this//You may also be using the default parameters to generate an image verification code//base64png: = Cap Tcha. Generatecaptchapngbase64stringdefault (Captchaid)//set JSON response//Set JSON response W.header (). Set ("Content-type", "Application/json;    Charset=utf-8 ") Body: = map[string]interface{}{" code ": 1," Data ": Base64png," Captchaid ": Captchaid," MSG ":" Success "} Json. Newencoder (W). Encode (body)}//Base64captcha Verify HTTP handlerfunc captchaverifyhandle (w http. Responsewriter, R *http. Request) {//parse requests parameters//Receive client to send the requested parameter decoder: = JSON. Newdecoder (R.body) var postparameters configjsonbody err: = decoder. Decode (&postparameters) if err! = Nil {log.   PRINTLN (ERR) } defer R.body.close ()//verify the CAPTCHA//Compare Image Verification code Verifyresult: = Base64captcha.verifycaptcha (Postparamet ERs. Id, Postparameters.verifyvalue)//set JSON response//Set JSON response W.header (). Set ("Content-type", "Application/json; Charset=utf-8 ") Body: = map[string]interface{}{" code ":" Error "," Data ":" Validation Failed "," MSG ":" Captcha Failed "} if Verifyre Sult {BODY = map[string]interface{}{"code": "Success", "Data": "Authenticated via", "MSG": "Captcha Verified"}} JSON. Newencoder (W). Encode (body)}//start a net/http server//start Golang net/http server func main () {//serve Vuejs+elementui+axios Web Applicatio N http. Handle ("/", HTTP. Fileserver (http. Dir ("./static")))//api for Create CAPTCHA//Create Image Verification code API HTTP. Handlefunc ("/api/getcaptcha", Generatecaptchahandler)//api for verify Captcha http. Handlefunc ("/api/verifycaptcha", Captchaverifyhandle) fmt. Println ("Server is at localhost:3333") if err: = http. Listenandserve ("localhost:3333", nil);   Err! = Nil {     Log. Fatal (ERR)}}

Run Demo code

cd $GOPATH/src/github.com/mojocn/captcha/examplesgo run main.go
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.