Skip to content

Instantly share code, notes, and snippets.

@tebeka
Created January 23, 2023 15:59
Show Gist options
  • Save tebeka/6f54421beb3932087fe78e6d1b4c1152 to your computer and use it in GitHub Desktop.
Save tebeka/6f54421beb3932087fe78e6d1b4c1152 to your computer and use it in GitHub Desktop.
/*
#golang #gem: Use expvar to expose metrics on /debug/vars.
*/
package main
import (
"expvar"
"fmt"
"log"
"net/http"
)
func addMetrics(name string, h http.Handler) http.Handler {
calls := expvar.NewInt(fmt.Sprintf("%s.calls", name))
// TODO: More metrics
fn := func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "OK")
}
func main() {
h := addMetrics("health", http.HandlerFunc(healthHandler))
http.Handle("/health", h)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalf("error: %s", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment