metric.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package metric
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "net/http"
  8. "time"
  9. )
  10. type (
  11. Value struct {
  12. Metric string `json:"metric"`
  13. Value float64 `json:"value"`
  14. Tags map[string]string `json:"tags"`
  15. }
  16. Values []*Value
  17. )
  18. func (m *Value) SetTag(key string, value string) *Value {
  19. if m.Tags == nil {
  20. m.Tags = make(map[string]string)
  21. }
  22. m.Tags[key] = value
  23. return m
  24. }
  25. func (m *Value) SetTags(tags map[string]string) *Value {
  26. for k, v := range tags {
  27. m.Tags[k] = v
  28. }
  29. return m
  30. }
  31. func (m *Value) Bytes() []byte {
  32. buf, _ := json.Marshal(m)
  33. return buf
  34. }
  35. func (m Values) Bytes() []byte {
  36. buf, _ := json.Marshal(m)
  37. return buf
  38. }
  39. func New(metric string, value float64) *Value {
  40. m := &Value{
  41. Metric: metric,
  42. Value: value,
  43. }
  44. m.Tags = make(map[string]string)
  45. return m
  46. }
  47. func Push(ctx context.Context, uri string, ms Values) (err error) {
  48. var (
  49. req *http.Request
  50. res *http.Response
  51. )
  52. if req, err = http.NewRequest("POST", uri, bytes.NewReader(ms.Bytes())); err != nil {
  53. return
  54. }
  55. cc, _ := context.WithTimeout(ctx, time.Second*5)
  56. if res, err = http.DefaultClient.Do(req.WithContext(cc)); err == nil {
  57. if !(res.StatusCode == 200 || res.StatusCode == 204) {
  58. err = errors.New("read response error:" + res.Status)
  59. }
  60. _ = res.Body.Close()
  61. }
  62. return
  63. }