From ea2c2c5d2e4ab73c8db66b71543a2b27614a6bd7 Mon Sep 17 00:00:00 2001 From: Catherine Date: Wed, 17 Sep 2025 15:36:27 +0000 Subject: [PATCH] [breaking-change] Add a health check endpoint. Also, simplify the listen endpoint configuration format. --- config.toml.example | 11 ++++------- src/config.go | 12 +++++------- src/health.go | 11 +++++++++++ src/main.go | 22 +++++++++++++++++----- 4 files changed, 37 insertions(+), 19 deletions(-) create mode 100644 src/health.go diff --git a/config.toml.example b/config.toml.example index e36aad4..a7bd20d 100644 --- a/config.toml.example +++ b/config.toml.example @@ -1,10 +1,7 @@ -[pages] -protocol = "tcp" -address = ":3333" - -[caddy] -protocol = "tcp" -address = ":3334" +[listen] +pages = "tcp/:3000" +caddy = "tcp/:3001" +health = "tcp/:3002" [wildcard] domain = "codeberg.page" diff --git a/src/config.go b/src/config.go index af5d7c1..3f9a10d 100644 --- a/src/config.go +++ b/src/config.go @@ -6,19 +6,17 @@ import ( "github.com/pelletier/go-toml/v2" ) -type ListenConfig struct { - Protocol string `toml:"protocol"` - Address string `toml:"address"` -} - type CacheConfig struct { MaxSize uint64 `toml:"max-size"` // in bytes MaxAge string `toml:"max-age"` } type Config struct { - Pages ListenConfig `toml:"pages"` - Caddy ListenConfig `toml:"caddy"` + Listen struct { + Pages string `toml:"pages"` + Caddy string `toml:"caddy"` + Health string `toml:"health"` + } `toml:"listen"` Wildcard struct { Domain string `toml:"domain"` CloneURL string `toml:"clone-url"` diff --git a/src/health.go b/src/health.go new file mode 100644 index 0000000..76625db --- /dev/null +++ b/src/health.go @@ -0,0 +1,11 @@ +package main + +import ( + "fmt" + "net/http" +) + +func ServeHealth(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + fmt.Fprintln(w, "ok") +} diff --git a/src/main.go b/src/main.go index d8cb00b..ccdb8f3 100644 --- a/src/main.go +++ b/src/main.go @@ -6,12 +6,18 @@ import ( "net" "net/http" "os" + "strings" ) var backend Backend -func serveHandler(name string, listen ListenConfig, serve func(http.ResponseWriter, *http.Request)) { - listener, err := net.Listen(listen.Protocol, listen.Address) +func serveHandler(name string, listen string, serve func(http.ResponseWriter, *http.Request)) { + protocol, address, ok := strings.Cut(listen, "/") + if !ok { + log.Fatalf("%s: %s: malformed endpoint", name, listen) + } + + listener, err := net.Listen(protocol, address) if err != nil { log.Fatalf("%s: %s\n", name, err) } @@ -73,9 +79,15 @@ func main() { log.Println("ready") - if config.Caddy != (ListenConfig{}) { - go serveHandler("caddy", config.Caddy, ServeCaddy) + go serveHandler("pages", config.Listen.Pages, ServePages) + + if config.Listen.Caddy != "" { + go serveHandler("caddy", config.Listen.Caddy, ServeCaddy) } - serveHandler("pages", config.Pages, ServePages) + if config.Listen.Health != "" { + go serveHandler("health", config.Listen.Health, ServeHealth) + } + + select {} }