feat(server): add health check endpoint

Ayman Bagabas created

Change summary

internal/client/client.go | 16 +++++++++++++++-
internal/server/proto.go  |  4 ++++
internal/server/server.go |  1 +
3 files changed, 20 insertions(+), 1 deletion(-)

Detailed changes

internal/client/client.go 🔗

@@ -3,6 +3,7 @@ package client
 import (
 	"context"
 	"encoding/json"
+	"fmt"
 	"net"
 	"net/http"
 	"path/filepath"
@@ -64,7 +65,7 @@ func (c *Client) Path() string {
 	return c.path
 }
 
-// GetGlobalConfig retrieves the server's configuration via RPC.
+// GetGlobalConfig retrieves the server's configuration.
 func (c *Client) GetGlobalConfig() (*config.Config, error) {
 	var cfg config.Config
 	rsp, err := c.h.Get("http://localhost/v1/config")
@@ -77,3 +78,16 @@ func (c *Client) GetGlobalConfig() (*config.Config, error) {
 	}
 	return &cfg, nil
 }
+
+// Health checks the server's health status.
+func (c *Client) Health() error {
+	rsp, err := c.h.Get("http://localhost/v1/health")
+	if err != nil {
+		return err
+	}
+	defer rsp.Body.Close()
+	if rsp.StatusCode != http.StatusOK {
+		return fmt.Errorf("server health check failed: %s", rsp.Status)
+	}
+	return nil
+}

internal/server/proto.go 🔗

@@ -21,6 +21,10 @@ type controllerV1 struct {
 	*Server
 }
 
+func (c *controllerV1) handleGetHealth(w http.ResponseWriter, r *http.Request) {
+	w.WriteHeader(http.StatusOK)
+}
+
 func (c *controllerV1) handleGetConfig(w http.ResponseWriter, r *http.Request) {
 	jsonEncode(w, c.cfg)
 }

internal/server/server.go 🔗

@@ -112,6 +112,7 @@ func NewServer(cfg *config.Config, network, address string) *Server {
 	p.SetUnencryptedHTTP2(true)
 	c := &controllerV1{Server: s}
 	mux := http.NewServeMux()
+	mux.HandleFunc("GET /v1/health", c.handleGetHealth)
 	mux.HandleFunc("GET /v1/config", c.handleGetConfig)
 	mux.HandleFunc("GET /v1/instances", c.handleGetInstances)
 	mux.HandleFunc("POST /v1/instances", c.handlePostInstances)