forked from circonus-labs/circonus-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
write.go
65 lines (55 loc) · 1.43 KB
/
write.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
// Copyright © 2018 Circonus, Inc. <support@circonus.com>
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
package api
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"github.com/pkg/errors"
)
func (c *Client) Write(groupID string, metrics *Metrics) error {
if groupID == "" {
return errors.New("invalid group id (empty)")
}
if metrics == nil {
return errors.New("invalid metrics (nil)")
}
if len(*metrics) == 0 {
return errors.New("invalid metrics (none)")
}
au, err := c.agentURL.Parse("/write/" + groupID)
if err != nil {
return errors.Wrap(err, "creating request url")
}
m, err := json.Marshal(metrics)
if err != nil {
return errors.Wrap(err, "converting metrics to JSON")
}
client := &http.Client{}
req, err := http.NewRequest("POST", au.String(), bytes.NewBuffer(m))
if err != nil {
return errors.Wrap(err, "preparing request")
}
resp, err := client.Do(req)
if err != nil {
return errors.Wrap(err, "request")
}
switch resp.StatusCode {
case http.StatusOK:
fallthrough
case http.StatusNoContent:
return nil // good, metrics were accepted
default:
// extract any error message and return
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, "reading response")
}
return errors.Errorf("%s - %s - %s", resp.Status, au.String(), strings.TrimSpace(string(data)))
}
}