为了账号安全,请及时绑定邮箱和手机立即绑定

解析嵌套在表单 urlencoded POST 中的 JSON 字符串

解析嵌套在表单 urlencoded POST 中的 JSON 字符串

Go
三国纷争 2023-07-31 17:02:50
我正在尝试解析 Mailgun 通知 Webhook 的一部分。这是一个带有x-www-form-urlencoded正文的 POST 请求。这是身体的一部分:sender: some@email.comattachments: [{"url": "https://storage.eu.mailgun.net/v3/domains/beep.boop/messages/randomstring/attachments/0", "content-type": "application/pdf", "name": "example.pdf", "size": 345}]"]该attachments值是一个json编码数组我想将这个字符串从 JSON 解码为StoredAttachment嵌套结构,因为我正在解码响应,x-www-form-urlencoded但我不知道该怎么做。目标structs如下:type NotifiedMessage struct {    Sender      string `schema:"sender"`    Subject     string `schema:"subject"`    Attachments []StoredAttachment `schema:"attachments"`    MessageUrl  string `schema:"message-url"`}// StoredAttachment structures contain information on an attachment associated with a stored message.type StoredAttachment struct {    Size        int    `json:"size"`    Url         string `json:"url"`    Name        string `json:"name"`    ContentType string `json:"content-type"`}这是到目前为止我的非工作代码:https ://play.golang.org/p/Ofbw2VAYV28
查看完整描述

1 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

您可以实现该TextUnmarshaler接口,schema包将使用该接口而不是执行默认过程,这允许自定义解组。


1.声明一个命名类型并将其用作字段的类型Attachments[]StoredAttachment是未命名的。因此,例如:

type AttachmentList []StoredAttachment

为什么?因为方法只能在命名类型上声明。

2.实现TextUnmarhsaler接口并在那里进行 json 解压缩。

func (ls *AttachmentList) UnmarshalText(text []byte) (err error) {
    return json.Unmarshal(text, (*[]StoredAttachment)(ls))
}

就是这样。

https://play.golang.org/p/t65mI7JRFfS


查看完整回答
反对 回复 2023-07-31
  • 1 回答
  • 0 关注
  • 96 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信