Blob


1 // package icinga provides a client to the Icinga2 HTTP API.
2 //
3 // A Client manages interaction with an Icinga2 server.
4 // It is created using Dial:
5 //
6 // client, err := icinga.Dial("icinga.example.com:5665", "icinga", "secret", http.DefaultClient)
7 // if err != nil {
8 // // handle error
9 // }
10 //
11 // Icinga2 servers in the wild often serve self-signed certificates which fail
12 // verification by Go's tls client. To ignore the errors, Dial the server with a
13 // modified http.Client:
14 //
15 // t := http.DefaultTransport.(*http.Transport)
16 // t.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
17 // c := http.DefaultClient
18 // c.Transport = t
19 // client, err := icinga.Dial(addr, user, pass, c)
20 // if err != nil {
21 // // handle error
22 // }
23 //
24 // Methods on Client provide API actions like looking up users and creating
25 // hosts:
26 //
27 // user, err := client.LookupUser("oliver")
28 // if err != nil {
29 // // handle error
30 // }
31 // host := Host{
32 // Name: "myserver.example.com",
33 // CheckCommand: "hostalive"
34 // Address: "192.0.2.1"
35 // Address6: "2001:db8::1"
36 // }
37 // if err := client.CreateHost(host); err != nil {
38 // // handle error
39 // }
40 //
41 // Since Client wraps http.Client, exported methods of http.Client such
42 // as Get and PostForm can be used to implement any extra functionality
43 // not provided by this package. For example:
44 //
45 // resp, err := client.PostForm("https://icinga.example.com:5665", data)
46 // if err != nil {
47 // // handle error
48 // }
49 //
50 package icinga
52 import (
53 "errors"
54 "net/http"
55 )
57 // A Client represents a client connection to the Icinga2 HTTP API.
58 // It should be created using Dial.
59 // Since Client wraps http.Client, exported methods such as Get and
60 // PostForm can be used to implement any functionality not provided by
61 // methods of Client.
62 type Client struct {
63 addr string
64 username string
65 password string
66 *http.Client
67 }
69 var ErrNotExist = errors.New("object does not exist")
70 var ErrExist = errors.New("object already exists")
71 var ErrNoMatch = errors.New("no object matches filter")
73 // Dial returns a new Client connected to the Icinga2 server at addr.
74 // The recommended value for client is http.DefaultClient.
75 // But it may also be a modified client which, for example,
76 // skips TLS certificate verification.
77 func Dial(addr, username, password string, client *http.Client) (*Client, error) {
78 c := &Client{addr, username, password, client}
79 if _, err := c.Permissions(); err != nil {
80 return nil, err
81 }
82 return c, nil
83 }
85 func (c *Client) Permissions() (response, error) {
86 resp, err := c.get("", "")
87 if err != nil {
88 return response{}, err
89 }
90 if resp.StatusCode == http.StatusOK {
91 return response{}, nil
92 }
93 return response{}, errors.New(resp.Status)
94 }