forked from nytm/go-grafana-api
-
Notifications
You must be signed in to change notification settings - Fork 1
/
response.go
84 lines (73 loc) · 1.58 KB
/
response.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
80
81
82
83
84
package gapi
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// NewResponse returns a new grafana API response
func NewResponse(res *http.Response, rerr error) *Response {
var data []byte
if rerr == nil && res.Body != nil {
data, _ = ioutil.ReadAll(res.Body)
}
return &Response{
res,
data,
rerr,
}
}
// Response is an API response
type Response struct {
*http.Response
data []byte
err error
}
// OK is true if there is no error
func (res *Response) OK() bool {
return res.Error() == nil
}
// BindJSON unmarshals the body into the given interface
func (res *Response) BindJSON(v interface{}) error {
return json.Unmarshal(res.data, v)
}
// Message returns the message from the
func (res *Response) Message() string {
data := struct {
Msg string `json:"message"`
}{}
res.BindJSON(&data)
return data.Msg
}
// ErrorMsg will return any error message that was returned as part of the JSON
// body. If you receive one of the errors defined in this package, you should
// also be able to extract the returned error message from the response object
// using this method.
func (res *Response) ErrorMsg() string {
var a map[string]string
if err := res.BindJSON(&a); err != nil {
return ""
}
return a["message"]
}
func (res *Response) Error() error {
if res.err != nil {
return res.err
}
switch res.StatusCode {
case 200:
return nil
case 404:
return ErrNotFound
case 409:
return ErrConflict
case 401:
return ErrNotAuthorized
case 412:
return ErrPreconditionFailed
case 500:
return ErrInternalServerError
default:
return fmt.Errorf(res.Status)
}
}