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, filter string) (*http.Response, error) {
33 u, err := url.Parse("https://" + c.addr + versionPrefix + path)
34 if err != nil {
35 return nil, err
36 }
37 if filter != "" {
38 v := url.Values{}
39 v.Set("filter", filter)
40 u.RawQuery = v.Encode()
41 }
42 req, err := NewRequest(http.MethodGet, u.String(), c.username, c.password, nil)
43 if err != nil {
44 return nil, err
45 }
46 return c.Do(req)
47 }
49 func (c *Client) post(path string, body io.Reader) (*http.Response, error) {
50 url := "https://" + c.addr + versionPrefix + path
51 req, err := NewRequest(http.MethodPost, url, c.username, c.password, body)
52 if err != nil {
53 return nil, err
54 }
55 return c.Do(req)
56 }
58 func (c *Client) put(path string, body io.Reader) (*http.Response, error) {
59 url := "https://" + c.addr + versionPrefix + path
60 req, err := NewRequest(http.MethodPut, url, c.username, c.password, body)
61 if err != nil {
62 return nil, err
63 }
64 return c.Do(req)
65 }
67 func (c *Client) delete(path string) (*http.Response, error) {
68 url := "https://" + c.addr + versionPrefix + path
69 req, err := NewRequest(http.MethodDelete, url, c.username, c.password, nil)
70 if err != nil {
71 return nil, err
72 }
73 return c.Do(req)
74 }