12 type object interface {
17 // jsonForCreate marshals obj into the required JSON object to be sent
18 // in the body of a PUT request to Icinga. Some fields of obj must not be set for
19 // Icinga to create the object. Since some of those fields are structs
20 // (and not pointers to structs), they are always included, even if unset.
21 // jsonForCreate overrides those fields to always be empty. Other fields are left
22 // alone to let Icinga report an error for us.
23 func jsonForCreate(obj object) ([]byte, error) {
24 m := make(map[string]interface{})
25 switch v := obj.(type) {
30 LastCheck *struct{} `json:",omitempty"`
31 LastCheckResult *struct{} `json:"last_check_result,omitempty"`
37 LastCheck *struct{} `json:",omitempty"`
38 LastCheckResult *struct{} `json:"last_check_result,omitempty"`
43 return nil, fmt.Errorf("marshal %T for creation unsupported", v)
45 return json.Marshal(m)
48 //go:generate ./crud.sh -o crud.go
50 func (c *Client) lookupObject(objpath string) (object, error) {
51 resp, err := c.get(objpath, "")
55 defer resp.Body.Close()
56 if resp.StatusCode == http.StatusNotFound {
57 return nil, ErrNotExist
59 iresp, err := parseResponse(resp.Body)
61 return nil, fmt.Errorf("parse response: %v", err)
62 } else if iresp.Error != nil {
63 return nil, iresp.Error
64 } else if resp.StatusCode != http.StatusOK {
65 return nil, errors.New(resp.Status)
67 return objectFromLookup(iresp)
70 func (c *Client) filterObjects(objpath, expr string) ([]object, error) {
71 resp, err := c.get(objpath, expr)
75 defer resp.Body.Close()
76 iresp, err := parseResponse(resp.Body)
78 return nil, fmt.Errorf("parse response: %v", err)
79 } else if iresp.Error != nil {
80 return nil, iresp.Error
81 } else if resp.StatusCode != http.StatusOK {
82 return nil, errors.New(resp.Status)
83 } else if len(iresp.Results) == 0 {
84 return nil, ErrNoMatch
86 return iresp.Results, nil
89 func (c *Client) createObject(obj object) error {
90 b, err := jsonForCreate(obj)
92 return fmt.Errorf("marshal into json: %v", err)
94 resp, err := c.put(obj.path(), bytes.NewReader(b))
98 if resp.StatusCode == http.StatusOK {
101 defer resp.Body.Close()
102 iresp, err := parseResponse(resp.Body)
104 return fmt.Errorf("parse response: %v", err)
106 if strings.Contains(iresp.Error.Error(), "already exists") {
112 func (c *Client) deleteObject(objpath string, cascade bool) error {
113 resp, err := c.delete(objpath, cascade)
117 defer resp.Body.Close()
118 if resp.StatusCode == http.StatusOK {
120 } else if resp.StatusCode == http.StatusNotFound {
123 iresp, err := parseResponse(resp.Body)
125 return fmt.Errorf("parse response: %v", err)