Blob


1 package icinga
3 import (
4 "fmt"
5 "io"
6 "net/http"
7 "net/url"
8 )
10 const versionPrefix = "/v1"
12 // NewRequest returns an authenticated HTTP request with appropriate header
13 // for sending to an Icinga2 server.
14 func NewRequest(method, url, username, password string, body io.Reader) (*http.Request, error) {
15 req, err := http.NewRequest(method, url, body)
16 if err != nil {
17 return nil, err
18 }
19 switch req.Method {
20 case http.MethodGet, http.MethodDelete:
21 req.Header.Set("Accept", "application/json")
22 case http.MethodPost, http.MethodPut:
23 req.Header.Set("Accept", "application/json")
24 req.Header.Set("Content-Type", "application/json")
25 default:
26 return nil, fmt.Errorf("new request: unsupported method %s", req.Method)
27 }
28 req.SetBasicAuth(username, password)
29 return req, nil
30 }
32 func (c *Client) get(path string) (*http.Response, error) {
33 url := "https://" + c.addr + versionPrefix + path
34 req, err := NewRequest(http.MethodGet, url, c.username, c.password, nil)
35 if err != nil {
36 return nil, err
37 }
38 return c.Do(req)
39 }
41 func (c *Client) getFilter(path, filter string) (*http.Response, error) {
42 u, err := url.Parse("https://" + c.addr + versionPrefix + path)
43 if err != nil {
44 return nil, err
45 }
46 v := url.Values{}
47 v.Set("filter", filter)
48 u.RawQuery = v.Encode()
49 req, err := NewRequest(http.MethodGet, u.String(), c.username, c.password, nil)
50 if err != nil {
51 return nil, err
52 }
53 return c.Do(req)
54 }
56 func (c *Client) post(path string, body io.Reader) (*http.Response, error) {
57 url := "https://" + c.addr + versionPrefix + path
58 req, err := NewRequest(http.MethodPost, url, c.username, c.password, body)
59 if err != nil {
60 return nil, err
61 }
62 return c.Do(req)
63 }
65 func (c *Client) put(path string, body io.Reader) (*http.Response, error) {
66 url := "https://" + c.addr + versionPrefix + path
67 req, err := NewRequest(http.MethodPut, url, c.username, c.password, body)
68 if err != nil {
69 return nil, err
70 }
71 return c.Do(req)
72 }
74 func (c *Client) delete(path string) (*http.Response, error) {
75 url := "https://" + c.addr + versionPrefix + path
76 req, err := NewRequest(http.MethodDelete, url, c.username, c.password, nil)
77 if err != nil {
78 return nil, err
79 }
80 return c.Do(req)
81 }