Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add health endpoint for NATS check and stop service if NATS closed #8

Merged
merged 1 commit into from
Nov 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package cmd
import (
"fmt"
"net/http"
_ "net/http/pprof"
"os"
"strings"

Expand Down Expand Up @@ -84,6 +85,7 @@ func start(cmd *cobra.Command, args []string) error {
go ex.WatchForServices(viper.GetInt("scrape_interval"))

http.Handle("/metrics", promhttp.Handler())
http.Handle("GET /healthz", http.HandlerFunc(health(nc)))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
resp := fmt.Sprintf("<html>" +
"<head><title>Micro Stats Exporter</title></head>" +
Expand All @@ -93,10 +95,26 @@ func start(cmd *cobra.Command, args []string) error {
fmt.Fprint(w, resp)
})

go func() {
for {
a := <-nc.StatusChanged(nats.CLOSED)
logr.Fatalf("NATS connection: %v", a)
}
}()

port := fmt.Sprintf(":%d", viper.GetInt("port"))
logr.Infof("starting server: %s", port)
return http.ListenAndServe(port, nil)
}

func health(nc *nats.Conn) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !nc.IsConnected() {
logr.Error("NATS is not connected")
http.Error(w, "internal server error", 500)
return
}
}
}

func newNatsConnection(name string) (*nats.Conn, error) {
Expand Down
Loading