remotewriter.go 842 B

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