You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言Lambda函数无法解析API Gateway请求体问题求助

API Gateway触发Go Lambda时请求体为空的问题

我使用Go语言实现了一个Lambda函数,通过API Gateway的POST方法作为事件触发器,相关配置在serverless.yml文件中。但遇到了一个问题:API请求体中的数据始终为空,无法进行解析。是否应该使用APIGatewayProxyRequest以外的类型?我尝试了多种方法,请求体内容始终无法被填充,希望能得到关于问题原因或该场景下正确处理请求体方法的见解。

main.go 代码实现

func handleRequest(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    log.Printf("Request Body: %v", request.Body)
    var requestBody RequestBody
    if request.Body == "" {
        return events.APIGatewayProxyResponse{
            StatusCode: 400,
            Body:       "Request body is empty",
        }, nil
    }

    err := json.Unmarshal([]byte(request.Body), &requestBody)
    if err != nil {
        log.Printf("Error unmarshalling JSON: %v", err)
        return events.APIGatewayProxyResponse{
            StatusCode: 400,
            Body:       "Invalid JSON input",
        }, nil
    }

    response := events.APIGatewayProxyResponse{
        StatusCode: 200,
        Body:       "Success",
    }

    return response, nil
}

serverless.yml 事件配置

events:
      - http:
          path: /test-method
          method: post
          integration: lambda
          private: true
          request:
            passThrough: NEVER
            template:
              application/json: ${file(templatefile)}

问题分析与解决方法

1. 核心问题:请求模板未正确传递请求体

你当前使用的是传统Lambda集成(integration: lambda),且设置了passThrough: NEVER,这要求必须通过请求模板明确将客户端的请求体映射到Lambda事件的body字段。如果你的templatefile内容没有正确配置,API Gateway就不会把请求体传递给Lambda,导致request.Body为空。

正确的模板文件内容应该是:

{
  "body": "$input.body"
}

这个模板会把API Gateway收到的原始请求体赋值给Lambda事件的body字段,你的Go代码就能正常读取到内容。

2. 更简单的方案:改用Lambda Proxy集成

如果不想手动配置模板,可以直接切换到Lambda Proxy集成,API Gateway会自动将整个请求(包括body、headers、查询参数等)封装成APIGatewayProxyRequest结构,无需额外配置。修改serverless.yml的事件配置:

events:
      - http:
          path: /test-method
          method: post
          private: true
          integration: lambda-proxy  # 修改为proxy集成

切换后,你的Go代码不需要任何改动,就能直接获取到请求体内容。

3. 验证请求的Content-Type

确保发送POST请求时,请求头的Content-Type设置为application/json。因为你的模板只配置了application/json类型的处理,如果请求的Content-Type不匹配,模板不会生效,也会导致请求体无法传递。


内容的提问来源于stack exchange,提问作者Nilay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 16:12:36