使用 golang 可以通过 prometheus 的 http API 查询指标。具体步骤如下:
- 导入必要的包
import (
"fmt"
"io/ioutil"
"net/http"
)
- 构建查询请求
url := "http://localhost:9090/api/v1/query?query=my_metric_total"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
// handle error
}
其中,my_metric_total 是待查询的指标名称。
- 发送请求并处理响应
resp, err := client.Do(req)
if err != nil {
// handle error
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(bodyBytes))
其中,client 是一个 http.Client 类型的实例,可以提前创建。上述代码中,我们将响应的 body 读取为 byte 数组并打印出来。如果查询成功,响应内容应该是一个 JSON 格式的字符串,其中包含了指定指标的查询结果。
需要注意的是,如果查询失败,可能会返回一些错误信息,此时需要根据 API 文档来解析响应内容。




