restructure check handlers

Signed-off-by: Christian Richter <crichter@owncloud.com>
This commit is contained in:
Christian Richter
2024-10-10 11:12:20 +02:00
parent c69a08dfbc
commit c86cc619c2
3 changed files with 47 additions and 15 deletions

View File

@@ -5,7 +5,6 @@ import (
"fmt"
"io"
"maps"
"net"
"net/http"
"golang.org/x/sync/errgroup"
@@ -92,7 +91,7 @@ func (h *CheckHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
g.SetLimit(h.conf.limit)
for name, check := range h.conf.checks {
g.Go(func() error {
g.Go(func() error { // https://go.dev/blog/loopvar-preview per iteration scope since go 1.22
if err := check(ctx); err != nil { // since go 1.22 for loops have a per-iteration scope instead of per-loop scope, no need to pin the check...
return fmt.Errorf("'%s': %w", name, err)
}
@@ -114,16 +113,3 @@ func (h *CheckHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.conf.logger.Panic().Err(err).Msg("failed to write response")
}
}
// NewTCPCheck returns a check that connects to a given tcp endpoint.
func NewTCPCheck(address string) func(ctx context.Context) error {
return func(ctx context.Context) error {
conn, err := net.Dial("tcp", address)
if err != nil {
return err
}
defer conn.Close()
return nil
}
}

View File

@@ -0,0 +1,23 @@
package handlers
import (
"context"
"fmt"
"github.com/nats-io/nats.go"
)
// NewNatsCheck checks the reachability of a nats server.
func NewNatsCheck(natsCluster string, options ...nats.Option) func(context.Context) error {
return func(ctx context.Context) error {
n, err := nats.Connect(natsCluster, options...)
if err != nil {
return fmt.Errorf("could not connect to nats server: %v", err)
}
defer n.Close()
if n.Status() != nats.CONNECTED {
return fmt.Errorf("nats server not connected")
}
return nil
}
}

View File

@@ -0,0 +1,23 @@
package handlers
import (
"context"
"net"
)
// NewTCPCheck returns a check that connects to a given tcp endpoint.
func NewTCPCheck(address string) func(ctx context.Context) error {
return func(ctx context.Context) error {
conn, err := net.Dial("tcp", address)
if err != nil {
return err
}
err = conn.Close()
if err != nil {
return err
}
return nil
}
}