我正在使用Go向bigpanda发出API发布请求。
https://docs.bigpanda.io/reference#create-plan
我有以下代码,当我尝试进行API发布时,由于对象错误而得到name
就是undefined
。
2019/08/23 18:38:04 {
"status" : "failure",
"error" : "{\"obj\":[{\"msg\":[\"'name' is undefined on object: {\\\"maintenance_plan\\\":{\\\"name\\\":\\\"\\\\\\\"name\\\\\\\": \\\\\\\"scheduled host maintenance\\\\\\\",\\\",\\\"condition\\\":\\\"\\\\\\\"condition\\\\\\\": {\\\\\\\"=\\\\\\\": [\\\\\\\"host\\\\\\\", \\\\\\\"prod-api-1\\\\\\\"]},\\\",\\\"start\\\":\\\"\\\\\\\"start\\\\\\\": \\\\\\\"1566514810\\\\\\\",\\\",\\\"end\\\":\\\"\\\\\\\"end\\\\\\\": \\\\\\\"156651600\\\\\\\"\\\"}}\"],\"args\":[]}]}"
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
type Maintenace_Plan struct {
Name string `json:"name"`
//Condition map[string]map[string][]string `json:condition`
Condition string `json:"condition"`
Start string `json:"start"`
End string `json:"end"`
}
type Payload struct {
Maintenace_Plan Maintenace_Plan `json:"maintenance_plan"`
}
func main() {
name := `"name": "scheduled host maintenance",`
create_plan := `"condition": {"=": ["host", "prod-api-1"]},`
start_time := `"start": "1566514810",`
end_time := `"end": "156651600"`
data := Payload{
Maintenace_Plan: Maintenace_Plan{
Name: name,
Condition: create_plan,
Start: start_time,
End: end_time,
},
}
payloadBytes, err := json.Marshal(data)
if err != nil {
fmt.Println(err)
}
body := bytes.NewReader(payloadBytes)
req, err := http.NewRequest("POST", "https://api.bigpanda.io/resources/v2.0/maintenance-plans", body)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer <token>")
resp, err := http.DefaultClient.Do(req)
defer resp.Body.Close()
body_1, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
log.Println(string(body_1))
}
看起来像身体不正确。 有什么办法可以修复代码。
答案 0 :(得分:2)
该错误消息可能是从您正在执行的API调用而非JSON元帅返回的。我怀疑这是由于您整理有效负载的方式-您正在将JSON写入字段,然后再进行JSON整理,所以最终得到的有效负载如下:
{"maintenance_plan":{"name":"\"name\": \"scheduled host maintenance\",","condition":"\"condition\": {\"=\": [\"host\", \"prod-api-1\"]},","start":"\"start\": \"1566514810\",","end":"\"end\": \"156651600\""}}
注意双“名称:” \ name \”。
解决方法如下:
data := Payload{
MaintenancePlan: MaintenancePlan{
Name: "scheduled host maintenance",
Condition: map[string][]string{
"=": []string{"host", "prod-api-1"},
},
StartTime: "1566514810",
EndTime: "156651600",
},
}
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(data)
if err != nil {
// Handle me
}
req, err := http.NewRequest(http.MethodPost, "https://foo/bar", &buf)
// continue