exmo/exmo.go

66 lines
1.0 KiB
Go

package exmo
import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
)
func Metrics(addr string) error {
http.Handle("/metrics", prometheus.Handler())
h, p, err := net.SplitHostPort(addr)
if err != nil {
return err
}
var u string
if h != "" {
u = fmt.Sprintf("http://%v:%v/metrics", h, p)
} else {
u = fmt.Sprintf("http://localhost:%v/metrics", p)
}
e := make(chan error)
go func() {
err := http.ListenAndServe(addr, nil)
if err != nil {
log.Printf("%+v", err)
}
e <- err
}()
go func() {
t := 100 * time.Millisecond
for {
time.Sleep(t)
if t < time.Minute {
t = t * 2
}
if t > 5*time.Second {
e <- errors.New("timeout waiting for metrics server to start")
}
resp, err := http.Get(u)
if err != nil {
log.Printf("%+v", err)
continue
}
io.Copy(ioutil.Discard, resp.Body)
if resp.StatusCode != http.StatusOK {
log.Printf("%+v", resp.Status)
} else {
e <- nil
return
}
}
}()
return <-e
}