metrics: allow server to return errors

This commit is contained in:
2023-07-08 21:13:31 -07:00
parent facd2f4f57
commit 6b6b22092e
3 changed files with 32 additions and 8 deletions

View File

@@ -8,6 +8,7 @@ import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/sync/errgroup"
"go.ntppool.org/common/logger"
)
@@ -41,7 +42,10 @@ func (m *Metrics) Handler() http.Handler {
})
}
func (m *Metrics) ListenAndServe(ctx context.Context, port int) {
// ListenAndServe starts a goroutine with a server running on
// the specified port. The server will shutdown and return when
// the provided context is done
func (m *Metrics) ListenAndServe(ctx context.Context, port int) error {
log := logger.Setup()
@@ -53,16 +57,23 @@ func (m *Metrics) ListenAndServe(ctx context.Context, port int) {
Handler: m.Handler(),
}
go func() {
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
err := srv.ListenAndServe()
if err != http.ErrServerClosed {
if err != nil && err != http.ErrServerClosed {
log.Warn("metrics server done listening", "err", err)
return err
}
}()
return nil
})
<-ctx.Done()
if err := srv.Shutdown(ctx); err != nil {
log.Error("metrics server shutdown failed", "err", err)
return err
}
return g.Wait()
}