Run a standalone metrics server¶
Sometimes you want metrics on their own port/listener — separate from your main
application server, typically bound to loopback or an internal address — rather than
mounted on the app mux. The opt-in metrics/server subpackage stands one up on
go/transport, so it shares the toolkit's lifecycle, graceful shutdown and TLS.
Importing metrics/server is the only thing that pulls go/transport into your
build; the core metrics package never does.
import (
"context"
transporthttp "gitlab.com/phpboyscout/go/transport/http"
metrics "gitlab.com/phpboyscout/go/transport-metrics"
metricsserver "gitlab.com/phpboyscout/go/transport-metrics/server"
)
func startMetrics(ctx context.Context) (*http.Server, error) {
m, err := metrics.New(
metrics.WithBuildInfo(metrics.BuildInfo{Version: version, Name: "mytool"}),
metrics.WithPprof(),
)
if err != nil {
return nil, err
}
// A dedicated server serving m's endpoint. Give it a loopback port so it is
// never externally reachable (the guard for a metrics port).
return metricsserver.New(ctx, transporthttp.ServerSettings{Port: 9090}, m)
}
Running and stopping it¶
server.New returns a *http.Server. Run and stop it with go/transport's
lifecycle helpers, or register those with a go/controls controller alongside your
application server so both start and stop together:
start := transporthttp.StartWithTLSPair(logger, srv, tlsPair) // controls.StartFunc
stop := transporthttp.Stop(logger, srv) // controls.StopFunc
See the go/transport docs for the full lifecycle and TLS options.
Attach, or standalone — or both¶
Use whichever fits:
- Attach (
metrics.Register(mux, …)) — one server, metrics alongside your API. Simplest; the app's auth guards it. - Standalone (
metrics/server) — metrics isolated on their own (loopback) port, independent lifecycle. Keeps scrape traffic off the app port.
A tool can even do both — mount a guarded /metrics on the public API and run a
loopback pprof server for local debugging.