Go Base64 验证码管理器

栏目: IT技术 · 发布时间: 6年前

内容简介:Base64 Captchas Manager, supports multiple(digit, math, audio, string, chinese etc.) and(memory, redis, memcached etc.).Preview:

Captchas

Base64 Captchas Manager, supports multiple(digit, math, audio, string, chinese etc.) and(memory, redis, memcached etc.).

Usage

Preview: http://129.204.189.159:10000/ .

$ cd example
$ go run main.go

Quick Start

package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"text/template"

	"github.com/clevergo/captchas"
	"github.com/clevergo/captchas/drivers"
	"github.com/clevergo/captchas/memstore"
)

var (
	store   = memstore.New()              // memory store.
	driver  = drivers.NewDigit()          // digit driver.
	manager = captchas.New(store, driver) // manager
	tmpl    = template.Must(template.New("captcha").Parse(`
<html>
<body>
<form action="/validate" method="POST">
	<input name="captcha">
	{{ .captcha.HTMLField "captcha_id" }}
	<input type="submit" value="Submit">
</form>
</body>
</html>
	`))
)

func main() {
	http.HandleFunc("/generate", generate)
	http.HandleFunc("/validate", validate)
	log.Println(http.ListenAndServe(":8080", http.DefaultServeMux))
}

// generates a new captcha
func generate(w http.ResponseWriter, r *http.Request) {
	captcha, err := manager.Generate()
	if err != nil {
		http.Error(w, err.Error(), 500)
                return
	}

	// returns JSON data.
	if r.URL.Query().Get("format") == "json" {
		v := map[string]string{
			"captcha_id":   captcha.ID(),             // captcha ID.
			"captcha_data": captcha.EncodeToString(), // base64 encode string.
		}
		data, _ := json.Marshal(v)
		w.Write(data)
		return
	}

	// render captcha via template.
	tmpl.Execute(w, map[string]interface{}{
		"captcha": captcha,
	})

}

// validates a captcha.
func validate(w http.ResponseWriter, r *http.Request) {
	captchaID := r.PostFormValue("captcha_id")
	captcha := r.PostFormValue("captcha")

	// verify
	if err := manager.Verify(captchaID, captcha, true); err != nil {
		io.WriteString(w, fmt.Sprintf("captcha is invalid: %s", err.Error()))
		return
	}

	io.WriteString(w, "valid")
}

Drivers

import "github.com/clevergo/captchas/drivers"

Digit

// all options are optional.
opts := []drivers.DigitOption{
	drivers.DigitHeight(50),
	drivers.DigitWidth(120),
	drivers.DigitLength(6),
	drivers.DigitMaxSkew(0.8),
	drivers.DigitDotCount(80),
}
driver := drivers.NewDigit(opts...)

Audio

// all options are optional.
opts := []drivers.AudioOption{
	drivers.AudioLangauge("en"),
	drivers.AudioLength(6),
}
driver := drivers.NewAudio(opts...)

Math

// all options are optional.
opts := []drivers.MathOption{
	drivers.MathHeight(50),
	drivers.MathWidth(120),
	drivers.MathNoiseCount(0),
	drivers.MathFonts([]string{}),
	drivers.MathBGColor(&color.RGBA{}),
}
driver := drivers.NewMath(opts...)

String

// all options are optional.
opts := []drivers.StringOption{
	drivers.StringHeight(50),
	drivers.StringWidth(120),
	drivers.StringLength(4),
	drivers.StringNoiseCount(0),
	drivers.StringFonts([]string{}),
	drivers.StringSource("abcdefghijklmnopqrstuvwxyz"),
	drivers.StringBGColor(&color.RGBA{}),
}
driver := drivers.NewString(opts...)

Chinese

// all options are optional.
opts := []drivers.ChineseOption{
	drivers.ChineseHeight(50),
	drivers.ChineseWidth(120),
	drivers.ChineseLength(4),
	drivers.ChineseNoiseCount(0),
	drivers.ChineseFonts([]string{"wqy-microhei.ttc"}),
	drivers.ChineseSource("零一二三四五六七八九十"),
	drivers.ChineseBGColor(&color.RGBA{}),
}
driver := drivers.NewChinese(opts...)

Stores

Memory

import "github.com/clevergo/captchas/memstore"
store := memstore.New(
	memstore.Expiration(10*time.Minute), // captcha expiration, optional.
	memstore.GCInterval(time.Minute), // garbage collection interval to delete expired captcha, optional.
)

Inspired by scs.memstore .

Redis

import (
    "github.com/clevergo/captchas/redisstore"
    "github.com/go-redis/redis/v7"
)
// redis client.
client := redis.NewClient(&redis.Options{
	Addr: "localhost:6379",
})
store := redisstore.New(
	client,
	redisstore.Expiration(expiration), // captcha expiration, optional.
	redisstore.Prefix("caotchas"), // redis key prefix, optional.
)

Memcached

import (
	"github.com/bradfitz/gomemcache/memcache"
	"github.com/clevergo/captchas/memcachedstore"
)
// client.
client := memcache.New("localhost:11211")
store := memcachedstore.New(
	client,
	memcachedstore.Expiration(int32(600)), // captcha expiration, optional.
	memcachedstore.Prefix("captchas"),     // key prefix, optional.
)

以上所述就是小编给大家介绍的《Go Base64 验证码管理器》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Think Python

Think Python

Allen B. Downey / O'Reilly Media / 2012-8-23 / GBP 29.99

Think Python is an introduction to Python programming for students with no programming experience. It starts with the most basic concepts of programming, and is carefully designed to define all terms ......一起来看看 《Think Python》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具