2025-04-02 10:16:07 +08:00

57 lines
1.4 KiB
Go

package common
import (
"net/http"
commonv1 "management/internal/erpserver/biz/v1/common"
"management/internal/pkg/config"
"management/internal/pkg/tpl"
)
type CaptchaHandler interface {
Captcha(w http.ResponseWriter, r *http.Request)
}
// captchaHandler 是 CaptchaHandler 接口的实现.
type captchaHandler struct {
conf *config.Captcha
render tpl.Renderer
biz commonv1.CaptchaBiz
}
// 确保 captchaHandler 实现了 CaptchaHandler 接口.
var _ CaptchaHandler = (*captchaHandler)(nil)
func NewCaptchaHandler(conf *config.Captcha, render tpl.Renderer, biz commonv1.CaptchaBiz) *captchaHandler {
return &captchaHandler{
conf: conf,
render: render,
biz: biz,
}
}
type CaptchaResponse struct {
CaptchaID string `json:"captcha_id"`
PicPath string `json:"pic_path"`
CaptchaLength int `json:"captcha_length"`
OpenCaptcha int `json:"open_captcha"`
}
func (h *captchaHandler) Captcha(w http.ResponseWriter, r *http.Request) {
keyLong := h.conf.KeyLong
oc := h.conf.OpenCaptcha
id, b64s, _, err := h.biz.Generate(h.conf.ImgHeight, h.conf.ImgWidth, keyLong, 0.7, 80)
if err != nil {
h.render.JSON(w, tpl.Response{Success: false, Message: "获取验证码失败"})
return
}
rsp := CaptchaResponse{
CaptchaID: id,
PicPath: b64s,
CaptchaLength: keyLong,
OpenCaptcha: oc,
}
h.render.JSON(w, tpl.Response{Success: true, Message: "ok", Data: rsp})
}