client.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package librato
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. )
  9. const Operations = "operations"
  10. const OperationsShort = "ops"
  11. type LibratoClient struct {
  12. Email, Token string
  13. }
  14. // property strings
  15. const (
  16. // display attributes
  17. Color = "color"
  18. DisplayMax = "display_max"
  19. DisplayMin = "display_min"
  20. DisplayUnitsLong = "display_units_long"
  21. DisplayUnitsShort = "display_units_short"
  22. DisplayStacked = "display_stacked"
  23. DisplayTransform = "display_transform"
  24. // special gauge display attributes
  25. SummarizeFunction = "summarize_function"
  26. Aggregate = "aggregate"
  27. // metric keys
  28. Name = "name"
  29. Period = "period"
  30. Description = "description"
  31. DisplayName = "display_name"
  32. Attributes = "attributes"
  33. // measurement keys
  34. MeasureTime = "measure_time"
  35. Source = "source"
  36. Value = "value"
  37. // special gauge keys
  38. Count = "count"
  39. Sum = "sum"
  40. Max = "max"
  41. Min = "min"
  42. SumSquares = "sum_squares"
  43. // batch keys
  44. Counters = "counters"
  45. Gauges = "gauges"
  46. MetricsPostUrl = "https://metrics-api.librato.com/v1/metrics"
  47. )
  48. type Measurement map[string]interface{}
  49. type Metric map[string]interface{}
  50. type Batch struct {
  51. Gauges []Measurement `json:"gauges,omitempty"`
  52. Counters []Measurement `json:"counters,omitempty"`
  53. MeasureTime int64 `json:"measure_time"`
  54. Source string `json:"source"`
  55. }
  56. func (c *LibratoClient) PostMetrics(batch Batch) (err error) {
  57. var (
  58. js []byte
  59. req *http.Request
  60. resp *http.Response
  61. )
  62. if len(batch.Counters) == 0 && len(batch.Gauges) == 0 {
  63. return nil
  64. }
  65. if js, err = json.Marshal(batch); err != nil {
  66. return
  67. }
  68. if req, err = http.NewRequest("POST", MetricsPostUrl, bytes.NewBuffer(js)); err != nil {
  69. return
  70. }
  71. req.Header.Set("Content-Type", "application/json")
  72. req.SetBasicAuth(c.Email, c.Token)
  73. if resp, err = http.DefaultClient.Do(req); err != nil {
  74. return
  75. }
  76. if resp.StatusCode != http.StatusOK {
  77. var body []byte
  78. if body, err = io.ReadAll(resp.Body); err != nil {
  79. body = []byte(fmt.Sprintf("(could not fetch response body for error: %s)", err))
  80. }
  81. err = fmt.Errorf("unable to post to Librato: %d %s %s", resp.StatusCode, resp.Status, string(body))
  82. }
  83. return
  84. }