feat(tfstate): bootstrap an http server that answers /healthz

This commit is contained in:
Julien Dessaux 2024-09-28 09:45:03 +02:00
parent 7dde5bf04e
commit 0f7e13222d
Signed by: adyxax
GPG key ID: F92E51B86E07177E
5 changed files with 116 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
tfstate

12
cmd/tfstate/healthz.go Normal file
View file

@ -0,0 +1,12 @@
package main
import "net/http"
func handleHealthz() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store, no-cache")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("{}"))
})
}

93
cmd/tfstate/main.go Normal file
View file

@ -0,0 +1,93 @@
package main
import (
"context"
"fmt"
"io"
"log"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"sync"
"time"
)
type Config struct {
Host string
Port string
}
func run(
ctx context.Context,
config *Config,
args []string,
getenv func(string) string,
stdin io.Reader,
stdout, stderr io.Writer,
) error {
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt)
defer cancel()
mux := http.NewServeMux()
addRoutes(
mux,
)
httpServer := &http.Server{
Addr: net.JoinHostPort(config.Host, config.Port),
Handler: mux,
}
go func() {
log.Printf("listening on %s\n", httpServer.Addr)
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Fprintf(os.Stderr, "error listening and serving: %+v\n", err)
}
}()
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
<-ctx.Done()
shutdownCtx := context.Background()
shutdownCtx, cancel := context.WithTimeout(shutdownCtx, 10*time.Second)
defer cancel()
if err := httpServer.Shutdown(shutdownCtx); err != nil {
fmt.Fprintf(os.Stderr, "error shutting down http server: %+v\n", err)
}
}()
wg.Wait()
return nil
}
func main() {
ctx := context.Background()
var opts *slog.HandlerOptions
if os.Getenv("TFSTATE_DEBUG") != "" {
opts = &slog.HandlerOptions{
AddSource: true,
Level: slog.LevelDebug,
}
}
logger := slog.New(slog.NewJSONHandler(os.Stdout, opts))
slog.SetDefault(logger)
config := Config{
Host: "0.0.0.0",
Port: "8080",
}
if err := run(
ctx,
&config,
os.Args,
os.Getenv,
os.Stdin,
os.Stdout, os.Stderr,
); err != nil {
fmt.Fprintf(os.Stderr, "%+v\n", err)
os.Exit(1)
}
}

7
cmd/tfstate/routes.go Normal file
View file

@ -0,0 +1,7 @@
package main
import "net/http"
func addRoutes(mux *http.ServeMux) {
mux.Handle("GET /healthz", handleHealthz())
}

3
go.mod Normal file
View file

@ -0,0 +1,3 @@
module git.adyxax.org/adyxax/tfstate
go 1.23.1