123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- package metric
- import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "net/http"
- "time"
- )
- type (
- Value struct {
- Metric string `json:"metric"`
- Value float64 `json:"value"`
- Tags map[string]string `json:"tags"`
- }
- Values []*Value
- )
- func (m *Value) SetTag(key string, value string) *Value {
- if m.Tags == nil {
- m.Tags = make(map[string]string)
- }
- m.Tags[key] = value
- return m
- }
- func (m *Value) SetTags(tags map[string]string) *Value {
- for k, v := range tags {
- m.Tags[k] = v
- }
- return m
- }
- func (m *Value) Bytes() []byte {
- buf, _ := json.Marshal(m)
- return buf
- }
- func (m Values) Bytes() []byte {
- buf, _ := json.Marshal(m)
- return buf
- }
- func New(metric string, value float64) *Value {
- m := &Value{
- Metric: metric,
- Value: value,
- }
- m.Tags = make(map[string]string)
- return m
- }
- func Push(ctx context.Context, uri string, ms Values) (err error) {
- var (
- req *http.Request
- res *http.Response
- )
- if req, err = http.NewRequest("POST", uri, bytes.NewReader(ms.Bytes())); err != nil {
- return
- }
- cc, _ := context.WithTimeout(ctx, time.Second*5)
- if res, err = http.DefaultClient.Do(req.WithContext(cc)); err == nil {
- if !(res.StatusCode == 200 || res.StatusCode == 204) {
- err = errors.New("read response error:" + res.Status)
- }
- _ = res.Body.Close()
- }
- return
- }
|