Skip to content

Instantly share code, notes, and snippets.

@chrisleavoy
Created April 28, 2025 20:06
Show Gist options
  • Save chrisleavoy/da17ed3d555ecf7bd929b47ecd880897 to your computer and use it in GitHub Desktop.
Save chrisleavoy/da17ed3d555ecf7bd929b47ecd880897 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/binary"
"fmt"
io_prometheus_client "github.com/prometheus/client_model/go"
"google.golang.org/protobuf/proto"
"io"
"net/http"
)
func main() {
url := "http://localhost:8888/metrics"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
panic(err)
}
req.Header.Set("Accept", "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
for {
// First read varint size
sizeBuf := make([]byte, 10) // Max varint size for 64-bit int
var bytesRead int
for i := 0; i < len(sizeBuf); i++ {
n, err := resp.Body.Read(sizeBuf[i : i+1])
if err != nil {
if err == io.EOF {
return // Done reading
}
panic(fmt.Sprintf("Failed reading size: %v", err))
}
bytesRead += n
if sizeBuf[i]&0x80 == 0 {
break // End of varint
}
}
size, _ := binary.Uvarint(sizeBuf[:bytesRead])
// Now read the message of that size
msgBuf := make([]byte, size)
_, err = io.ReadFull(resp.Body, msgBuf)
if err != nil {
panic(fmt.Sprintf("Failed reading message body: %v", err))
}
mf := &io_prometheus_client.MetricFamily{}
err = proto.Unmarshal(msgBuf, mf)
if err != nil {
panic(fmt.Sprintf("Failed to unmarshal: %v", err))
}
fmt.Printf("Metric: %s, Type: %s\n", mf.GetName(), mf.GetType().String())
for _, m := range mf.Metric {
fmt.Print(" Labels: {")
for i, label := range m.Label {
if i > 0 {
fmt.Print(", ")
}
fmt.Printf("%s=\"%s\"", label.GetName(), label.GetValue())
}
fmt.Println("}")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment