我正在嘗試解析 Mailgun 通知 Webhook 的一部分。這是一個帶有x-www-form-urlencoded正文的 POST 請求。這是身體的一部分:sender: [email protected]: [{"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
- 1 回答
- 0 關注
- 171 瀏覽
添加回答
舉報
0/150
提交
取消