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

AWS Lambda函数URL调用时Go JSON结构体解析失败求助

Lambda函数URL调用需额外解析请求体的原因及解决方法

是的,通过Lambda函数URL调用时必须添加额外的解析逻辑,因为函数URL的请求格式和控制台测试事件完全不同。

问题根源

控制台测试事件是直接将你输入的JSON作为处理函数的入参传递,但通过函数URL调用时,Lambda收到的是一个封装后的请求结构体(对应events.APIGatewayV2HTTPRequest),你的ContactForm结构体字段会被初始化为零值(nil、0、空字符串),因为Lambda无法自动从封装结构中提取出你需要的业务JSON。

解决步骤

  1. 修改入参类型:将处理函数的第二个参数改为events.APIGatewayV2HTTPRequest,需先导入AWS Lambda Go事件包:github.com/aws/aws-lambda-go/events。
  2. 手动解析请求体:从APIGatewayV2HTTPRequest的Body字段中取出JSON字符串,反序列化为ContactForm结构体。
  3. 处理Base64编码情况:如果请求体是Base64编码的(IsBase64Encoded为true),需要先解码。

修改后的示例代码

import (
    "context"
    "encoding/base64"
    "encoding/json"
    "fmt"

    "github.com/aws/aws-lambda-go/events"
)

type ContactForm struct {
    Phone     int     `json:"phone"`
    Email     string  `json:"email"`
    Business  string  `json:"business"`
    Message   string  `json:"message"`
    Name      string  `json:"name"`
    File_data *string `json:"file_data"`
    File_name *string `json:"file_name"`
    Uri       *string
}

func HandleRequest(ctx context.Context, req events.APIGatewayV2HTTPRequest) {
    // 处理Base64编码的请求体
    body := req.Body
    if req.IsBase64Encoded {
        decoded, err := base64.StdEncoding.DecodeString(body)
        if err != nil {
            fmt.Printf("解码请求体失败: %v", err)
            return
        }
        body = string(decoded)
    }

    // 反序列化为ContactForm结构体
    var contactForm ContactForm
    err := json.Unmarshal([]byte(body), &contactForm)
    if err != nil {
        fmt.Printf("解析JSON失败: %v", err)
        return
    }

    // 原业务逻辑保持不变
    if contactForm.File_data != nil && contactForm.File_name != nil {
        uri := create_file(*contactForm.File_data, *contactForm.File_name)
        contactForm.Uri = &uri
    }

    fmt.Printf("%v", contactForm)

    bodyContent := create_email_body(contactForm)
    sendEmail(contactForm.Business, bodyContent)
}

额外说明

  • 函数URL的请求结构体包含了请求头、查询参数、请求体等所有HTTP请求信息,你可以根据需要提取其他元数据。
  • 测试时确保Postman/XHR请求的Content-Type设置为application/json,否则请求体可能无法正确解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 19:48:35