I'm making an API post request to bigpanda using Go.
https://docs.bigpanda.io/reference#create-plan
I have below code and when I try to make API post getting name
is undefined
on object error.
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))
}
Looks like body is incorrect. Is there any way to fix the code.
That error message is probably being returned from the API Call you're making and not the JSON Marshal. I suspect it's due to the way you're marshalling your payload - you're writing JSON to the fields and then JSON marshalling it so you end up with a payload that looks like:
{"maintenance_plan":{"name":"\"name\": \"scheduled host maintenance\",","condition":"\"condition\": {\"=\": [\"host\", \"prod-api-1\"]},","start":"\"start\": \"1566514810\",","end":"\"end\": \"156651600\""}}
Notice the double "name: " ame\".
The way to fix it would be to do something like:
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