Files
jh-zz/clients/jd/common.go

79 lines
1.6 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package jd
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"jhman/clients"
"net/http"
"time"
"github.com/redis/go-redis/v9"
)
const base = "https://smart.jdbox.xyz:58001"
func Post(path string, data any, auth ...bool) (io.ReadCloser, error) {
reqBytes, err := json.Marshal(data)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", base+path, bytes.NewReader(reqBytes))
if err != nil {
return nil, err
}
defer req.Body.Close()
req.Header.Set("Content-Type", "application/json")
if len(auth) == 0 || auth[0] {
token, err := Token()
if err != nil {
return nil, fmt.Errorf("获取令牌失败: %w", err)
}
req.Header.Set("X-Token", token)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s 响应失败: %s", path, resp.Status)
}
return resp.Body, nil
}
func Token() (string, error) {
// 尝试从 Redis 获取缓存的 token
token, err := clients.Redis.Get(context.Background(), "token").Result()
if err != nil && !errors.Is(err, redis.Nil) {
return "", fmt.Errorf("获取 token 失败: %w", err)
}
if token != "" {
return token, nil
}
// 如果缓存中没有 token则进行认证请求
resp, err := ClientAuth()
if err != nil {
return "", fmt.Errorf("认证请求失败: %w", err)
}
// 返回请求的 token
token = resp.Data
if err := clients.Redis.Set(context.Background(), "token", token, 6*24*time.Hour).Err(); err != nil {
return "", fmt.Errorf("缓存 token 失败: %w", err)
}
return token, nil
}