go-zero/core/stat/remotewriter.go

55 lines
1.0 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package stat
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"time"
"github.com/zeromicro/go-zero/core/logx"
2020-07-26 17:09:05 +08:00
)
2022-04-28 11:25:26 +08:00
const (
httpTimeout = time.Second * 5
jsonContentType = "application/json; charset=utf-8"
)
2020-07-26 17:09:05 +08:00
// ErrWriteFailed is an error that indicates failed to submit a StatReport.
2020-07-26 17:09:05 +08:00
var ErrWriteFailed = errors.New("submit failed")
// A RemoteWriter is a writer to write StatReport.
2020-07-26 17:09:05 +08:00
type RemoteWriter struct {
endpoint string
}
// NewRemoteWriter returns a RemoteWriter.
2020-07-26 17:09:05 +08:00
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, jsonContentType, bytes.NewReader(bs))
2020-07-26 17:09:05 +08:00
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
}