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