1. package main
    2. import (
    3. "bytes"
    4. "encoding/json"
    5. "io/ioutil"
    6. "log"
    7. "math/rand"
    8. "net/http"
    9. "time"
    10. )
    11. type MetricValue struct {
    12. Metric string `json:"metric"`
    13. Nid string `json:"nid"`
    14. Endpoint string `json:"endpoint"`
    15. Timestamp int64 `json:"timestamp"`
    16. Step int64 `json:"step"`
    17. ValueUntyped interface{} `json:"value"`
    18. Value float64 `json:"-"`
    19. CounterType string `json:"counterType"`
    20. Tags string `json:"tags"`
    21. TagsMap map[string]string `json:"tagsMap"` //保留2种格式,方面后端组件使用
    22. }
    23. func main() {
    24. log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
    25. t1 := time.NewTicker(10 * time.Second)
    26. for {
    27. //数据上报的api
    28. url := "http://127.0.0.1:7900/api/transfer/push"
    29. resp, err := push(url, getMetricValues())
    30. if err != nil {
    31. log.Println(err)
    32. }
    33. log.Println(string(resp))
    34. <-t1.C
    35. }
    36. }
    37. func getMetricValues() []*MetricValue {
    38. ret := []*MetricValue{}
    39. now := time.Now().Unix()
    40. ts := now - now%10 // 对齐时间戳
    41. r1 := rand.Intn(20)
    42. tagsMap := make(map[string]string) //自定义的tag
    43. ret = append(ret, &MetricValue{
    44. Nid: "41", //页面上鼠标移动到节点上看到的节点ID
    45. Metric: "mock.qps",
    46. ValueUntyped: float64(1),
    47. Timestamp: ts,
    48. CounterType: "GAUGE",
    49. Step: 10,
    50. TagsMap: tagsMap,
    51. })
    52. }
    53. func push(url string, v interface{}) (response []byte, err error) {
    54. bs, err := json.Marshal(v)
    55. if err != nil {
    56. return response, err
    57. }
    58. bf := bytes.NewBuffer(bs)
    59. resp, err := http.Post(url, "application/json", bf)
    60. if err != nil {
    61. return response, err
    62. }
    63. defer resp.Body.Close()
    64. return ioutil.ReadAll(resp.Body)
    65. }