#### 为什么base64图片 for RESTful 服务
Data URIs 支持大部分浏览器,IE8之后也支持.
小图片使用base64响应对于RESTful服务来说更便捷
CSS Image 嵌入base64图片
```css
div.image {
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA...);
}
```
HTML 嵌入base64图片`img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..."`
#### [godoc文档](https://godoc.org/github.com/mojocn/base64Captcha)
#### 在线Demo [Playground Powered by Vuejs+elementUI+Axios](http://captcha.mojotv.cn)
[![Playground](https://raw.githubusercontent.com/mojocn/base64Captcha/master/examples/static/captcha.png "Playground")](http://captcha.mojotv.cn/ "Playground")
## 快速开始
#### 安装golang包
go get -u github.com/mojocn/base64Captcha
#### 使用golang搭建API服务
```go
package main
import (
"encoding/json"
"fmt"
"github.com/mojocn/base64Captcha"
"log"
"net/http"
"strconv"
)
// base64Captcha verify http handler
// golang 比较图像验证码 返回json
func captchaVerifyHandle(w http.ResponseWriter, r *http.Request) {
//接收客户端发送来的请求参数
r.ParseForm()
formData := r.Form
captchaId := formData.Get("captchaId")
captchaDigits := formData.Get("captchaDigits")
//比较图像验证码
verifyResult := base64Captcha.VerifyCaptcha(captchaId, captchaDigits)
//设置json响应
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
// 接收idKey字符串 返回base64 Data URIs 图像验证码json
func generateCaptchaHandler(w http.ResponseWriter, r *http.Request) {
//接收客户端发送来的请求参数
r.ParseForm()
formData := r.Form
//图像验证码的idKey 客户端返回.如果使用到传统web服务,idKey服务器生成设置cookie里面
captchaId := formData.Get("captchaId")
//下面的参数都是图像验证码的外观参数,可以不设置条用base64Captcha.GenerateCaptchaPngBase64StringDefault(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"))
//利用base64Captcha,创建base64图像验证码
base64Png := base64Captcha.GenerateCaptchaPngBase64String(captchaId, PngWidth, PngHeight, DotCount, DefaultLen, MaxSkew)
//你也可以是用默认参数 生成图像验证码
//base64Png := captcha.GenerateCaptchaPngBase64StringDefault(captchaId)
//设置json响应
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)
}
//启动golang net/http 服务器
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 主要方法
- 自定参数返回验证码base64png 返回base64 Data URIs
`func GenerateCaptchaPngBase64String(identifier string, pngWidth, pngHeight, DotCount, digitsLen int, maxSkew float64) string`
- 使用默认配置 返回base64 Data URIs,默认参数 width=240 height=70 dot-count=20 digits-len=6 skew-factor=0.7
`func GenerateCaptchaPngBase64StringDefault(identifier string) string `
- 比较返回的数字图像验证码的正确性
`func VerifyCaptcha(identifier, digits string) bool`
- 参数随机的idKey
`func RandomId() string`
- 更详细文档请查看[godoc](https://godoc.org/github.com/mojocn/base64Captcha)
#### 运行demo代码
cd $GOPATH/src/github.com/mojocn/captcha/examples
go run main.go
#### 访问 [http://localhost:777](http://localhost:777)
#### golang-demo nginx 反向代理配置 `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;
}
```
[如果觉得这教程有用请访问GitHub 提Issue Star Fork](https://github.com/mojocn/base64Captcha/wiki/%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B/_edit)
有疑问加站长微信联系(非本文作者)