client.go 2.2 KB

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