我已經嘗試了這兩個版本的 AWS Go 開發工具包,每次我收到一條錯誤訊息,指出詳細資訊欄位格式不正確。詳細資訊欄位接受 JSON 字串。
在 SDK V2 中,您基本上有一個事件結構
type Event struct {
Details []struct {
Key string `json:"Key"`
Value string `json:"Value"`
} `json:"Details"`
DetailType string `json:"DetailType"`
Source string `json:"Source"`
}
然后,該示例使用此代碼構建 JSON 字串
myDetails := "{ "
for _, d := range event.Details {
myDetails = myDetails "\"" d.Key "\": \"" d.Value "\","
}
myDetails = myDetails " }"
然后進行 api 呼叫
input := &cloudwatchevents.PutEventsInput{
Entries: []types.PutEventsRequestEntry{
{
Detail: &myDetails,
DetailType: &event.DetailType,
Resources: []string{
*lambdaARN,
},
Source: &event.Source,
},
},
}
基本上我收到一條錯誤訊息,指出分配給 Detail 欄位的字串格式錯誤。我相信這是因為示例代碼生成了一個帶有無效結尾的字串。但是,當您省略 時,您將獲得一個零記憶體參考。
AWS 開發工具包示例
SDK 版本 1 的示例也會產生錯誤。
任何幫助都會很棒
uj5u.com熱心網友回復:
您鏈接的頁面上的代碼不是 100% 正確的。他們實際上鏈接了頁面底部的“完整示例”,其代碼略有不同:
https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/gov2/cloudwatch/PutEvent/PutEventv2.go#L108-L117
myDetails := "{ "
for i, d := range event.Details {
if i == (len(event.Details) - 1) {
myDetails = myDetails "\"" d.Key "\": \"" d.Value "\""
} else {
myDetails = myDetails "\"" d.Key "\": \"" d.Value "\","
}
}
myDetails = myDetails " }"
但是,正如您已經發現的那樣,像這樣構建 JSON 并不理想且容易出錯。
我提出以下建議:
details := make(map[string]string, len(event.Details))
for _, d := range event.Details {
details[d.Key] = d.Value
}
b, err := json.Marshal(details)
if err != nil {
return
}
fmt.Println(string(b))
查看 Playground 以查看它的實際效果:
https://play.golang.com/p/E4ueZLGIKp4
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/438853.html
標籤:亚马逊网络服务 走 aws-lambda aws-事件桥
上一篇:在Go中組合不同的排序
