-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathrest.go
79 lines (69 loc) · 1.96 KB
/
rest.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package ari
import (
"fmt"
"net/url"
"github.com/jmcvetta/napping"
)
//
// napping Post/Get/Delete wrappers
//
// Post does POST request
func (c *Client) Post(path string, payload, results interface{}) error {
_, err := c.PostWithResponse(path, payload, results)
return err
}
// PostWithResponse does POST request and returns the response
func (c *Client) PostWithResponse(path string, payload, results interface{}) (*napping.Response, error) {
url := c.makeURL(path)
var errMsg errorResponse
c.Log("Sending POST request to %s", url)
res, err := c.session.Post(url, payload, results, &errMsg)
if results != nil {
c.setClientRecurse(results)
}
return res, c.checkNappingError(res, err, errMsg)
}
// Get does GET request
func (c *Client) Get(path string, p *url.Values, results interface{}) error {
url := c.makeURL(path)
var errMsg errorResponse
c.Log("Sending GET request to %s", url)
res, err := c.session.Get(url, p, results, &errMsg)
if results != nil {
c.setClientRecurse(results)
}
return c.checkNappingError(res, err, errMsg)
}
// Delete does DELETE request
func (c *Client) Delete(path string, results interface{}) error {
url := c.makeURL(path)
var errMsg errorResponse
c.Log("Sending DELETE request to %s", url)
res, err := c.session.Delete(url, nil, results, &errMsg)
if results != nil {
c.setClientRecurse(results)
}
return c.checkNappingError(res, err, errMsg)
}
type errorResponse struct {
Message string
}
func (c *Client) makeURL(path string) string {
return fmt.Sprintf("%s/ari%s", c.endpoint, path)
}
func (c *Client) checkNappingError(res *napping.Response, err error, errMsg errorResponse) error {
if err != nil {
return err
}
status := res.Status()
if status > 299 {
err := fmt.Errorf("Non-2XX returned by server (%s)", res.HttpResponse().Status)
if errMsg.Message != "" {
err = fmt.Errorf("%s: %s", err.Error(), errMsg.Message)
}
c.Log(fmt.Sprintf(" - %s", err.Error()))
return err
}
c.Log(" - Success")
return err
}