Files

163 lines
4.5 KiB
Go

// Package httpadapter HTTP 上游通道适配器(Day 33):调用上游短信 API,
// 支持 GET/POST 与可配置鉴权(none/appkey/sign-HMAC),统一解析 JSON 响应。
package httpadapter
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// AuthType 鉴权方式。
type AuthType string
// 支持的鉴权方式。
const (
AuthNone AuthType = "none" // 无鉴权
AuthAppKey AuthType = "appkey" // 请求头 X-App-Key
AuthSign AuthType = "sign" // X-Timestamp + X-Sign(HMAC-SHA256(secret, ts+"."+payload))
)
// ErrBadUpstream 上游响应不合法/失败。
var ErrBadUpstream = errors.New("httpadapter: 上游返回失败")
// Config 适配器配置。
type Config struct {
Endpoint string // 上游地址(完整 URL)
Method string // GET / POST(默认 POST)
AuthType AuthType // 鉴权方式(默认 none)
AppKey string // appkey 模式的 key
Secret string // sign 模式的密钥
Timeout time.Duration // 默认 5s
Client *http.Client // 测试注入;默认复用包级客户端
}
// sharedCli 包级客户端(连接复用)。
var sharedCli = &http.Client{Timeout: 5 * time.Second}
// Adapter HTTP 通道适配器。
type Adapter struct{ cfg Config }
// New 构造(补默认值)。
func New(cfg Config) *Adapter {
if cfg.Method == "" {
cfg.Method = http.MethodPost
}
cfg.Method = strings.ToUpper(cfg.Method)
if cfg.AuthType == "" {
cfg.AuthType = AuthNone
}
if cfg.Timeout <= 0 {
cfg.Timeout = 5 * time.Second
}
if cfg.Client == nil {
cfg.Client = sharedCli
}
return &Adapter{cfg: cfg}
}
// SendReq 发送请求。
type SendReq struct {
Mobile string `json:"mobile"`
Content string `json:"content"`
SrcID string `json:"src_id,omitempty"` // 扩展码/长号码
TaskID string `json:"task_id,omitempty"` // 幂等/关联任务
}
// SendResp 发送响应。
type SendResp struct {
MessageID string // 上游消息 ID
Raw string // 原始响应体(诊断)
}
// upResp 上游统一响应契约:{code, msg, data:{message_id}}。
type upResp struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
MessageID string `json:"message_id"`
} `json:"data"`
}
// Send 调用上游:GET(query)/POST(JSON body);按 AuthType 注入鉴权头。
// 验收:成功调用上游发送接口并解析返回值(message_id)。
func (a *Adapter) Send(ctx context.Context, req *SendReq) (*SendResp, error) {
var (
httpReq *http.Request
payload []byte // 参与签名的载荷
err error
)
switch a.cfg.Method {
case http.MethodGet:
q := url.Values{}
q.Set("mobile", req.Mobile)
q.Set("content", req.Content)
if req.SrcID != "" {
q.Set("src_id", req.SrcID)
}
if req.TaskID != "" {
q.Set("task_id", req.TaskID)
}
payload = []byte(q.Encode())
httpReq, err = http.NewRequestWithContext(ctx, http.MethodGet, a.cfg.Endpoint+"?"+q.Encode(), nil)
default: // POST(JSON)
payload, err = json.Marshal(req)
if err != nil {
return nil, err
}
httpReq, err = http.NewRequestWithContext(ctx, http.MethodPost, a.cfg.Endpoint, bytes.NewReader(payload))
}
if err != nil {
return nil, err
}
if err := a.applyAuth(httpReq, payload); err != nil {
return nil, err
}
if httpReq.Body != nil || a.cfg.Method == http.MethodPost {
httpReq.Header.Set("Content-Type", "application/json")
}
resp, err := a.cfg.Client.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("httpadapter: 请求上游失败: %w", err)
}
defer func() { _ = resp.Body.Close() }()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("%w: HTTP %d: %s", ErrBadUpstream, resp.StatusCode, string(raw))
}
var up upResp
if err := json.Unmarshal(raw, &up); err != nil {
return nil, fmt.Errorf("httpadapter: 上游响应解析失败: %w", err)
}
if up.Code != 0 {
return nil, fmt.Errorf("%w: code=%d msg=%s", ErrBadUpstream, up.Code, up.Msg)
}
return &SendResp{MessageID: up.Data.MessageID, Raw: string(raw)}, nil
}
// applyAuth 注入鉴权头(appkey/sign)。
func (a *Adapter) applyAuth(req *http.Request, payload []byte) error {
switch a.cfg.AuthType {
case AuthAppKey:
req.Header.Set("X-App-Key", a.cfg.AppKey)
case AuthSign:
ts := strconv.FormatInt(time.Now().Unix(), 10)
mac := hmac.New(sha256.New, []byte(a.cfg.Secret))
mac.Write([]byte(ts + "." + string(payload)))
req.Header.Set("X-Timestamp", ts)
req.Header.Set("X-Sign", hex.EncodeToString(mac.Sum(nil)))
}
return nil
}