11 const versionPrefix = "/v1"
13 // NewRequest returns an authenticated HTTP request with appropriate header
14 // for sending to an Icinga2 server.
15 func NewRequest(method, url, username, password string, body io.Reader) (*http.Request, error) {
16 req, err := http.NewRequest(method, url, body)
21 case http.MethodGet, http.MethodDelete:
22 req.Header.Set("Accept", "application/json")
23 case http.MethodPost, http.MethodPut:
24 req.Header.Set("Accept", "application/json")
25 req.Header.Set("Content-Type", "application/json")
27 return nil, fmt.Errorf("new request: unsupported method %s", req.Method)
29 req.SetBasicAuth(username, password)
33 // filterEncode url-encodes the filter expression expr in the required
34 // format to be included in a request. Notably, spaces need to be encoded
35 // as "%20", not "+" as returned by the url package.
36 func filterEncode(expr string) string {
39 return strings.ReplaceAll(v.Encode(), "+", "%20")
42 func (c *Client) get(path, filter string) (*http.Response, error) {
43 u, err := url.Parse("https://" + c.addr + versionPrefix + path)
48 u.RawQuery = filterEncode(filter)
50 req, err := NewRequest(http.MethodGet, u.String(), c.username, c.password, nil)
57 func (c *Client) post(path string, body io.Reader) (*http.Response, error) {
58 url := "https://" + c.addr + versionPrefix + path
59 req, err := NewRequest(http.MethodPost, url, c.username, c.password, body)
66 func (c *Client) put(path string, body io.Reader) (*http.Response, error) {
67 url := "https://" + c.addr + versionPrefix + path
68 req, err := NewRequest(http.MethodPut, url, c.username, c.password, body)
75 func (c *Client) delete(path string, cascade bool) (*http.Response, error) {
76 u, err := url.Parse("https://" + c.addr + versionPrefix + path)
83 u.RawQuery = v.Encode()
85 req, err := NewRequest(http.MethodDelete, u.String(), c.username, c.password, nil)