remotewriter.go 1009 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package stat
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "net/http"
  7. "time"
  8. "git.i2edu.net/i2/go-zero/core/logx"
  9. )
  10. const httpTimeout = time.Second * 5
  11. // ErrWriteFailed is an error that indicates failed to submit a StatReport.
  12. var ErrWriteFailed = errors.New("submit failed")
  13. // A RemoteWriter is a writer to write StatReport.
  14. type RemoteWriter struct {
  15. endpoint string
  16. }
  17. // NewRemoteWriter returns a RemoteWriter.
  18. func NewRemoteWriter(endpoint string) Writer {
  19. return &RemoteWriter{
  20. endpoint: endpoint,
  21. }
  22. }
  23. func (rw *RemoteWriter) Write(report *StatReport) error {
  24. bs, err := json.Marshal(report)
  25. if err != nil {
  26. return err
  27. }
  28. client := &http.Client{
  29. Timeout: httpTimeout,
  30. }
  31. resp, err := client.Post(rw.endpoint, "application/json", bytes.NewBuffer(bs))
  32. if err != nil {
  33. return err
  34. }
  35. defer resp.Body.Close()
  36. if resp.StatusCode != http.StatusOK {
  37. logx.Errorf("write report failed, code: %d, reason: %s", resp.StatusCode, resp.Status)
  38. return ErrWriteFailed
  39. }
  40. return nil
  41. }