Golang / GoLang Production Patterns and Web Standards Interview Questions
How do you add observability (metrics and distributed tracing) to a Go service?
Production Go services expose Prometheus metrics and OpenTelemetry traces. Both integrate with Go's standard HTTP server and context-based propagation.
// Prometheus metrics with the standard prometheus/client_golang library
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
httpRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests",
},
[]string{"method", "path", "status"},
)
httpRequestDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request duration in seconds",
Buckets: prometheus.DefBuckets,
},
[]string{"method", "path"},
)
)
func init() {
prometheus.MustRegister(httpRequestsTotal, httpRequestDuration)
}
// Metrics middleware
func metricsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
lrw := &statusResponseWriter{ResponseWriter: w, status: 200}
next.ServeHTTP(lrw, r)
dur := time.Since(start).Seconds()
path := r.URL.Path
httpRequestsTotal.WithLabelValues(r.Method, path,
strconv.Itoa(lrw.status)).Inc()
httpRequestDuration.WithLabelValues(r.Method, path).Observe(dur)
})
}
// Expose metrics endpoint
mux.Handle("GET /metrics", promhttp.Handler())
// OpenTelemetry tracing (simplified)
// otel.SetTracerProvider(tp)
// tracer := otel.Tracer("myservice")
// ctx, span := tracer.Start(ctx, "operationName")
// defer span.End()
// span.SetAttributes(attribute.String("user.id", userID))
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
