-
Notifications
You must be signed in to change notification settings - Fork 1
/
remotewriter.go
48 lines (38 loc) · 842 Bytes
/
remotewriter.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
package stat
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"time"
"github.com/sjclijie/go-zero/core/logx"
)
const httpTimeout = time.Second * 5
var ErrWriteFailed = errors.New("submit failed")
type RemoteWriter struct {
endpoint string
}
func NewRemoteWriter(endpoint string) Writer {
return &RemoteWriter{
endpoint: endpoint,
}
}
func (rw *RemoteWriter) Write(report *StatReport) error {
bs, err := json.Marshal(report)
if err != nil {
return err
}
client := &http.Client{
Timeout: httpTimeout,
}
resp, err := client.Post(rw.endpoint, "application/json", bytes.NewBuffer(bs))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
logx.Errorf("write report failed, code: %d, reason: %s", resp.StatusCode, resp.Status)
return ErrWriteFailed
}
return nil
}