31 lines
861 B
Go
31 lines
861 B
Go
package handlers
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/base64"
|
|
"net/http"
|
|
|
|
"github.com/dchest/captcha"
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"go-dy/internal/resp"
|
|
)
|
|
|
|
// CaptchaNewHandler generates a new captcha and returns id + base64 image.
|
|
func CaptchaNewHandler() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
id := captcha.New()
|
|
var buf bytes.Buffer
|
|
// generate PNG image of the captcha
|
|
const width, height = 200, 80
|
|
if err := captcha.WriteImage(&buf, id, width, height); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "message": "captcha generate failed"})
|
|
return
|
|
}
|
|
b64 := base64.StdEncoding.EncodeToString(buf.Bytes())
|
|
resp.OK(c, gin.H{
|
|
"id": id,
|
|
"image": "data:image/png;base64," + b64,
|
|
})
|
|
}
|
|
} |