2 Commits

Author SHA1 Message Date
lzh
2e8f0cb3f2 sms_tool 2025-06-20 14:49:45 +08:00
yuguojian
992f39109d 优化ip缓存 2025-06-18 18:06:45 +08:00
2 changed files with 28 additions and 13 deletions

View File

@@ -19,11 +19,10 @@ type HuaChenIpClient struct {
cache ICacheAdapter
}
func NewHuaChenIpClient(appCode string, cache ICacheAdapter) *HuaChenIpClient {
func NewHuaChenIpClient(appCode string) *HuaChenIpClient {
return &HuaChenIpClient{
AppCode: appCode,
Host: "https://c2ba.api.huachen.cn",
cache: cache,
}
}
@@ -90,13 +89,19 @@ func (h *HuaChenIpClient) GetIpInfo(ip string) (res *ApiResult, err error) {
return &apiResult, nil
}
func (h *HuaChenIpClient) GetIpInfoFormCache(ctx context.Context, ip string, ttl time.Duration) (res *ApiResult, err error) {
getCache, err := h.cache.Get(ctx, h.ipKey(ip))
if err != nil {
return nil, errors.Wrapf(err, "获取缓存失败ip:%s", ip)
}
if getCache != nil {
return getCache, nil
func (h *HuaChenIpClient) Set(cache ICacheAdapter) {
h.cache = cache
}
func (h *HuaChenIpClient) GetIpInfoFormCache(ctx context.Context, ip string, opt ...time.Duration) (res *ApiResult, err error) {
if h.cache != nil {
res, err = h.cache.Get(ctx, h.ipKey(ip))
if err != nil {
return nil, errors.Wrapf(err, "获取缓存失败ip:%s", ip)
}
if res != nil {
return res, nil
}
}
res, err = h.GetIpInfo(ip)
if err != nil {
@@ -109,9 +114,11 @@ func (h *HuaChenIpClient) GetIpInfoFormCache(ctx context.Context, ip string, ttl
return nil, errors.Wrapf(err, "无法将IP信息转换为JSONip:%s", ip)
}
err = h.cache.Set(ctx, h.ipKey(ip), string(infoJson), ttl)
if err != nil {
return nil, errors.Wrapf(err, "缓存ip:%s信息失败", ip)
if len(opt) == 0 {
err = h.cache.Set(ctx, h.ipKey(ip), string(infoJson), opt[0])
if err != nil {
return nil, errors.Wrapf(err, "缓存ip:%s信息失败", ip)
}
}
return
}

View File

@@ -70,7 +70,15 @@ func (c *SmsClient) GetCode(ctx context.Context, key string) (code string, err e
if err != nil {
return "", err
}
return value.(string), nil
if value == nil {
return "", errors.New("验证码不存在,请重新发送")
}
switch value.(type) {
case string:
return value.(string), nil
default:
return "", errors.New("验证码类型错误,请联系管理员")
}
}
// SaveCode 保存验证码