package main
import("flag""github.com/gin-gonic/gin""math/rand")funcmain(){
listenAddress := flag.String("addr",":8001","Address on which to expose metrics and web interface.")
flag.Parse()
r := gin.Default()
r.GET("/prome_http_sd", httpSd)
r.Run(*listenAddress)// listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")}
编写target数据结构
type target struct{
Targets []string`json:"targets"`
Labels map[string]string`json:"labels"`}
编写 httpSd 处理函数
frn返回一个最大值为n的随机整数
randMapKeys 作为随机标签的key
randMapValues 作为随机标签的value
遍历nodes切片mock target数据
返回targets json数据
funchttpSd(c *gin.Context){
nodes :=[]string{"172.20.70.205:9115","http://prometheus.io","http://www.baidu.com","https://www.baidu.com","https://github.com/",}
randMapKeys :=[]string{"arch","idc","os","job"}
randMapValues :=[]string{"linux","beijing","centos","arm64"}
frn :=func(n int)int{return rand.Intn(n)}
targets :=make([]target,0)for_, n :=range nodes {
num :=len(randMapKeys)
m :=make(map[string]string, num)for i :=0; i < num; i++{
m[randMapKeys[frn(len(randMapKeys)-1)]]= randMapValues[frn(len(randMapValues)-1)]}
t := target{
Targets:[]string{n},
Labels: m,}
targets =append(targets, t)}
c.JSON(200, targets)}
完整go代码
package main
import("flag""github.com/gin-gonic/gin""math/rand")funcmain(){
listenAddress := flag.String("addr",":8001","Address on which to expose metrics and web interface.")
flag.Parse()
r := gin.Default()
r.GET("/prome_http_sd", httpSd)
r.Run(*listenAddress)// listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")}type target struct{
Targets []string`json:"targets"`
Labels map[string]string`json:"labels"`}funchttpSd(c *gin.Context){
nodes :=[]string{"172.20.70.205:9115","http://prometheus.io","http://www.baidu.com","https://www.baidu.com","https://github.com/",}
randMapKeys :=[]string{"arch","idc","os","job"}
randMapValues :=[]string{"linux","beijing","centos","arm64"}
frn :=func(n int)int{return rand.Intn(n)}
targets :=make([]target,0)for_, n :=range nodes {
num :=len(randMapKeys)
m :=make(map[string]string, num)for i :=0; i < num; i++{
m[randMapKeys[frn(len(randMapKeys)-1)]]= randMapValues[frn(len(randMapValues)-1)]}
t := target{
Targets:[]string{n},
Labels: m,}
targets =append(targets, t)}
c.JSON(200, targets)}