You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
rition/rition-probe/client/http.go

78 lines
1.6 KiB

package client
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
type ReportDataItem struct {
Metric string `json:"metric,omitempty"`
Value any `json:"value,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
Timestamp int64 `json:"timestamp"`
}
type DataItem struct {
Metric string `json:"metric,omitempty"`
Value any `json:"value,omitempty"`
Timestamp int64 `json:"timestamp"`
}
type ReportResponse struct {
RequestId string `json:"request_id,omitempty"`
Message string `json:"message,omitempty"`
}
func (c *Client) Report(dataItem []DataItem) (*ReportResponse, error) {
tags := map[string]string{
"instanceId": c.config.InstanceId,
"hostname": c.config.HostName,
}
// convert data
reportDataItems := make([]ReportDataItem, 0, len(dataItem))
for _, item := range dataItem {
reportDataItems = append(reportDataItems, ReportDataItem{
Metric: item.Metric,
Value: item.Value,
Tags: tags,
Timestamp: time.Now().Unix(),
})
}
reportJsonBytes, err := json.Marshal(reportDataItems)
if err != nil {
return nil, err
}
// send report data
resp, err := http.Post(c.config.CenterServer, "application/json", bytes.NewBuffer(reportJsonBytes))
if err != nil {
return nil, err
}
// get response
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
respBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
fmt.Println(string(respBytes))
response := ReportResponse{}
err = json.Unmarshal(respBytes, &response)
if err != nil {
return nil, err
}
return &response, nil
}