Skip to content

Commit

Permalink
[Gateway] Simple healthcheck endpoint (#10786)
Browse files Browse the repository at this point in the history
  • Loading branch information
bolekk authored Sep 26, 2023
1 parent 739bfae commit 95989d7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
14 changes: 14 additions & 0 deletions core/services/gateway/network/httpserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ type httpServer struct {
lggr logger.Logger
}

const (
HealthCheckPath = "/health"
HealthCheckResponse = "OK"
)

func NewHttpServer(config *HTTPServerConfig, lggr logger.Logger) HttpServer {
baseCtx, cancelBaseCtx := context.WithCancel(context.Background())
server := &httpServer{
Expand All @@ -64,6 +69,7 @@ func NewHttpServer(config *HTTPServerConfig, lggr logger.Logger) HttpServer {
}
mux := http.NewServeMux()
mux.Handle(config.Path, http.HandlerFunc(server.handleRequest))
mux.Handle(HealthCheckPath, http.HandlerFunc(server.handleHealthCheck))
server.server = &http.Server{
Addr: fmt.Sprintf("%s:%d", config.Host, config.Port),
Handler: mux,
Expand All @@ -75,6 +81,14 @@ func NewHttpServer(config *HTTPServerConfig, lggr logger.Logger) HttpServer {
return server
}

func (s *httpServer) handleHealthCheck(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte(HealthCheckResponse))
if err != nil {
s.lggr.Debug("error when writing response for healthcheck", err)
}
}

func (s *httpServer) handleRequest(w http.ResponseWriter, r *http.Request) {
source := http.MaxBytesReader(nil, r.Body, s.config.MaxRequestBytes)
rawMessage, err := io.ReadAll(source)
Expand Down
13 changes: 13 additions & 0 deletions core/services/gateway/network/httpserver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io"
"net/http"
"strings"
"testing"

"github.com/stretchr/testify/mock"
Expand Down Expand Up @@ -74,3 +75,15 @@ func TestHTTPServer_HandleRequest_RequestBodyTooBig(t *testing.T) {
resp := sendRequest(t, url, []byte("0123456789"))
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
}

func TestHTTPServer_HandleHealthCheck(t *testing.T) {
server, _, url := startNewServer(t, 100_000, 100_000)
defer server.Close()

url = strings.Replace(url, HTTPTestPath, network.HealthCheckPath, 1)
resp := sendRequest(t, url, []byte{})
respBytes, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
require.Equal(t, []byte(network.HealthCheckResponse), respBytes)
}

0 comments on commit 95989d7

Please sign in to comment.