首页
/ 使用Req库中间件统一处理API响应与错误

使用Req库中间件统一处理API响应与错误

2025-06-13 10:59:06作者:牧宁李

在Go语言生态中,Req是一个功能强大的HTTP客户端库,它提供了丰富的特性来简化HTTP请求的处理。本文将深入探讨如何使用Req的中间件机制来统一处理API响应和错误,构建更加健壮的HTTP客户端。

中间件机制的核心价值

Req库的中间件机制允许开发者在请求生命周期的不同阶段插入自定义逻辑。这种设计模式特别适合处理以下场景:

  1. 统一错误处理
  2. 响应数据标准化
  3. 日志记录
  4. 认证和授权
  5. 性能监控

通过中间件,我们可以避免在每个API调用处重复相同的处理逻辑,实现DRY(Don't Repeat Yourself)原则。

构建自定义客户端

首先,我们需要创建一个自定义的客户端结构体,嵌入Req的标准客户端,并添加我们的中间件逻辑:

type APIError struct {
    Code    int
    Message string `json:"message"`
}

func (e *APIError) Error() string {
    return fmt.Sprintf("API Error: %s (Code: %d)", e.Message, e.Code)
}

type Client struct {
    *req.Client
}

func NewClient() *Client {
    c := req.C().
        SetBaseURL("https://api.example.com").
        SetCommonErrorResult(&APIError{}).
        OnAfterResponse(func(client *req.Client, resp *req.Response) error {
            // 中间件逻辑将在这里实现
            return nil
        })
    
    return &Client{c}
}

中间件处理层次

在OnAfterResponse中间件中,我们可以分层次处理不同类型的响应:

1. 底层错误处理

首先处理网络错误、编解码错误等底层问题:

if resp.Err != nil {
    resp.Err = fmt.Errorf("%s\nraw content:\n%s", resp.Err.Error(), resp.Dump())
    return nil
}

2. API业务错误处理

处理服务器返回的业务错误:

if err, ok := resp.ErrorResult().(*APIError); ok {
    resp.Err = err
    return nil
}

3. 成功响应处理

对于成功的响应,我们可以进行统一的数据处理:

if resp.IsSuccess() {
    // 检查响应码是否符合预期
    if resp.StatusCode != http.StatusOK {
        resp.Err = fmt.Errorf("unexpected status code: %d", resp.StatusCode)
        return nil
    }
    
    // 可以在这里添加统一的响应数据转换逻辑
}

业务API封装

通过中间件处理了通用逻辑后,业务API的实现变得非常简洁:

type UserProfile struct {
    Name string `json:"name"`
    Blog string `json:"blog"`
}

func (c *Client) GetUserProfile(username string) (*UserProfile, error) {
    var user *UserProfile
    err := c.Get("/users/{username}").
        SetPathParam("username", username).
        Do().
        Into(&user)
    return user, err
}

高级技巧

响应数据标准化

可以在中间件中对成功的响应数据进行标准化处理:

type StandardResponse struct {
    Code    int         `json:"code"`
    Message string      `json:"message"`
    Data    interface{} `json:"data"`
}

// 在中间件中
if resp.IsSuccess() {
    var stdResp StandardResponse
    if err := resp.ToJSON(&stdResp); err == nil {
        // 处理标准化响应
    }
}

性能监控

可以在中间件中添加请求耗时统计:

start := time.Now()
defer func() {
    duration := time.Since(start)
    metrics.RecordAPIRequest(resp.Request.URL.Path, duration, resp.StatusCode)
}()

最佳实践

  1. 错误处理一致性:确保所有错误都通过相同的方式处理和记录
  2. 日志规范化:在中间件中统一记录请求和响应日志
  3. 重试机制:可以在中间件中实现自动重试逻辑
  4. 熔断保护:集成熔断器模式防止级联故障
  5. 请求追踪:添加分布式追踪ID

通过合理使用Req的中间件机制,我们可以构建出高度可维护、可扩展的HTTP客户端,大幅提升开发效率和系统稳定性。

登录后查看全文
热门项目推荐
相关项目推荐