base64Captcha

package module
v0.0.0-...-25ddfb2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 14, 2018 License: Apache-2.0 Imports: 15 Imported by: 0

README

Base64 Encoding Captcha for RESTful application

Go Report Card GoDoc

Package base64Captcha creates base64-encoding png for digits captcha. base64Captcha is used for rapid development of RESTful APIs, web apps and backend services in Go. give a string identifier to the package and it returns with a base64-encoding-png-string

Why Base64 Image for RESTful Application
  Data URIs are now supported by all major browsers. IE supports embedding images since version 8 as well.
  RESTful Application retruns small base64 image is more convenient.

CSS Image Embedding Example

div.image {
  background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA...);
}

HTML Image Embedding Example

<img alt="Embedded Image" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />
Documentation
Playground Powered by Vuejs+elementUI+Axios

Playground

Quick Start

Download and Install
go get -u github.com/mojocn/base64Captcha
use base64Captcha quick start a API server
package main

import (
	"encoding/json"
	"fmt"
	"github.com/mojocn/base64Captcha"
	"log"
	"net/http"
	"strconv"
)

// base64Captcha verify http handler
func captchaVerifyHandle(w http.ResponseWriter, r *http.Request) {
	//parse request parameters
	r.ParseForm()
	formData := r.Form
	captchaId := formData.Get("captchaId")
	captchaDigits := formData.Get("captchaDigits")

	//verify the captcha
	verifyResult := base64Captcha.VerifyCaptcha(captchaId, captchaDigits)

	//set json response
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	body := map[string]interface{}{"code": "error", "data": "验证失败", "msg": "captcha failed", "debug": formData}
	if verifyResult {
		body = map[string]interface{}{"code": "success", "data": "验证通过", "msg": "captcha verified", "debug": formData}
	}
	json.NewEncoder(w).Encode(body)
}

// base64Captcha create http handler
func generateCaptchaHandler(w http.ResponseWriter, r *http.Request) {
	//parse request parameters

	r.ParseForm()
	formData := r.Form
	captchaId := formData.Get("captchaId")
	DotCount, _ := strconv.Atoi(formData.Get("DotCount"))
	MaxSkew, _ := strconv.ParseFloat(formData.Get("MaxSkew"), 64)
	PngWidth, _ := strconv.Atoi(formData.Get("PngWidth"))
	PngHeight, _ := strconv.Atoi(formData.Get("PngHeight"))
	DefaultLen, _ := strconv.Atoi(formData.Get("DefaultLen"))

	//create base64 encoding captcha
	base64Png := base64Captcha.GenerateCaptchaPngBase64String(captchaId, PngWidth, PngHeight, DotCount, DefaultLen, MaxSkew)
	//or you can do this
	//base64Png := captcha.GenerateCaptchaPngBase64StringDefault(captchaId)

	//set json response
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	body := map[string]interface{}{"code": 1, "data": base64Png, "msg": "success", "debug": formData}
	json.NewEncoder(w).Encode(body)
}

//start a net/http server
func main() {
	//serve Vuejs+ElementUI+Axios Web Application
	http.Handle("/", http.FileServer(http.Dir("./static")))
	//api for create captcha
	http.HandleFunc("/api/getCaptcha", generateCaptchaHandler)
	//api for verify captcha
	http.HandleFunc("/api/verifyCaptcha", captchaVerifyHandle)

	fmt.Println("Server is at localhost:777")
	if err := http.ListenAndServe(":777", nil); err != nil {
		log.Fatal(err)
	}
}
base64Captcha package function
  • func GenerateCaptchaPngBase64String(identifier string, pngWidth, pngHeight, DotCount, digitsLen int, maxSkew float64) string return base64-png-captcha
  • func GenerateCaptchaPngBase64StringDefault(identifier string) string default settings width=240 height=70 dot-count=20 digits-len=6 skew-factor=0.7
  • func VerifyCaptcha(identifier, digits string) bool verify the captcha-png-numbers by identifierKey
  • func RandomId() string Server Create Random IdentifierKey
Build and Run the Demo
cd $GOPATH/src/github.com/mojocn/captcha/examples
go run main.go
demo nginx configuration captcha.mojotv.cn.config
server {
        listen 80;
        server_name captcha.mojotv.cn;
        charset utf-8;

        location / {
            try_files /_not_exists_ @backend;
        }
        location @backend {
           proxy_set_header X-Forwarded-For $remote_addr;
           proxy_set_header Host $http_host;
           proxy_pass http://127.0.0.1:777;
        }
        access_log  /home/wwwlogs/captcha.mojotv.cn.log;
}
Go to http://localhost:777

Congratulations! You've just built your first base64Captcha-APIs app. Any question you can leave a message. If you like the package please star this repo

License

base64Captcha source code is licensed under the Apache Licence, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html).

Documentation

Overview

Package base64Captcha create base64 encoding captcha png. designed for APPs service. 创建base64格式图像验证码,为APIs服务而设计.

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultLen Default number of digits in captcha solution.
	// 默认数字验证长度.
	DefaultLen = 6
	// CollectNum The number of captchas created that triggers garbage collection used by default store.
	// 默认图像验证GC清理的上限个数
	CollectNum = 100000
	// Expiration time of captchas used by default store.
	// 内存保存验证码的时限
	Expiration = 10 * time.Minute

	// PngWidth Captcha png width in pixel.
	// 图像验证码的宽度像素
	PngWidth = 240
	// PngHeight png height in pixel.
	// 图像验证码的高度像素.
	PngHeight = 80
	// MaxSkew max absolute skew factor of a single digit.
	// 图像验证码的最大干扰洗漱.
	MaxSkew = 0.7
	// DotCount Number of background circles.
	// 图像验证码干扰圆点的数量.
	DotCount = 20
)

Functions

func GenerateCaptchaPngBase64String

func GenerateCaptchaPngBase64String(identifier string, pngWidth, pngHeight, dotCount, digitsLen int, maxSkew float64) string

GenerateCaptchaPngBase64String customize captcha image by identifier, width, height, dot-count, digits-length, skew-factor. default settings width=240 height=70 dot-count=20 digits-len=6 skew-factor=0.7. return base64 png string. 自定义参数返回base64编码的图像验证码

func GenerateCaptchaPngBase64StringDefault

func GenerateCaptchaPngBase64StringDefault(identifier string) string

GenerateCaptchaPngBase64StringDefault use default value create captcha png by identifier string. return base64 png string. 默认参数生成数字图像验证码

func RandomDigits

func RandomDigits(length int) []byte

RandomDigits returns a byte slice of the given length containing pseudorandom numbers in range 0-9. The slice can be used as a captcha solution.

func RandomId

func RandomId() string

RandomId returns a new random id key string. golang服务器端产生随机的idKey

func VerifyCaptcha

func VerifyCaptcha(identifier, digits string) bool

VerifyCaptcha the captcha image. identifier is the key of the captcha. digits numbers in captcha image. return boolean value. 验证图像验证码,返回boolean.

Types

type Image

type Image struct {
	*image.Paletted
	// contains filtered or unexported fields
}

Image digits captcha Struct

func NewImage

func NewImage(id string, digits []byte, width, height int) *Image

NewImage returns a new captcha image of the given width and height with the given digits, where each digit must be in range 0-9.

func (*Image) WriteTo

func (m *Image) WriteTo(w io.Writer) (int64, error)

WriteTo writes captcha image in PNG format into the given writer.

func (*Image) WriteToBase64String

func (m *Image) WriteToBase64String() string

WriteToBase64String convert image to base64 encodeing string

type Store

type Store interface {
	// Set sets the digits for the captcha id.
	Set(id string, digits []byte)

	// Get returns stored digits for the captcha id. Clear indicates
	// whether the captcha must be deleted from the store.
	Get(id string, clear bool) (digits []byte)
}

Store An object implementing Store interface can be registered with SetCustomStore function to handle storage and retrieval of captcha ids and solutions for them, replacing the default memory store.

It is the responsibility of an object to delete expired and used captchas when necessary (for example, the default memory store collects them in Set method after the certain amount of captchas has been stored.)

func NewMemoryStore

func NewMemoryStore(collectNum int, expiration time.Duration) Store

NewMemoryStore returns a new standard memory store for captchas with the given collection threshold and expiration time (duration). The returned store must be registered with SetCustomStore to replace the default one.

Directories

Path Synopsis
example of HTTP server that uses the captcha package.
example of HTTP server that uses the captcha package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL