diff --git a/.gitignore b/.gitignore index 16b96b8..5e79ec2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ go-sample-app +hello_server diff --git a/go.mod b/go.mod index b205825..84ea164 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,6 @@ module github.com/harness/go-sample-app go 1.15 require ( - github.com/gorilla/context v1.1.1 + github.com/gorilla/context v1.1.1 // indirect github.com/gorilla/mux v1.6.2 ) diff --git a/go.sum b/go.sum index 28737c4..45c53cf 100644 --- a/go.sum +++ b/go.sum @@ -1,4 +1,4 @@ +github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/mux v1.6.2 h1:Pgr17XVTNXAk3q/r4CpKzC5xBM/qW1uVLV+IhRZpIIk= github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= - diff --git a/hello_server.go b/hello_server.go index df038fd..e643fce 100644 --- a/hello_server.go +++ b/hello_server.go @@ -19,6 +19,12 @@ func handler(w http.ResponseWriter, r *http.Request) { w.Write([]byte(CreateGreeting(name))) } +func healthzHandler(w http.ResponseWriter, r *http.Request) { + log.Printf("Health check request received") + w.WriteHeader(http.StatusOK) + w.Write([]byte("OK\n")) +} + func CreateGreeting(name string) string { if name == "" { name = "Guest" @@ -31,6 +37,7 @@ func main() { r := mux.NewRouter() r.HandleFunc("/", handler) + r.HandleFunc("/healthz", healthzHandler) srv := &http.Server{ Handler: r, diff --git a/hello_server_test.go b/hello_server_test.go index a3f5cd3..f704c57 100644 --- a/hello_server_test.go +++ b/hello_server_test.go @@ -1,6 +1,7 @@ package main import ( - + "net/http" + "net/http/httptest" "time" "testing" ) @@ -36,6 +37,31 @@ func TestGreetingDefault(t *testing.T) { t.Errorf("Greeting was incorrect, got: %s, want: %s.", greeting, "Hello, Guest\n") } } + +func TestHealthzEndpoint(t *testing.T) { + req, err := http.NewRequest("GET", "/healthz", nil) + if err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + handler := http.HandlerFunc(healthzHandler) + + handler.ServeHTTP(rr, req) + + // Check the status code is what we expect + if status := rr.Code; status != http.StatusOK { + t.Errorf("handler returned wrong status code: got %v want %v", + status, http.StatusOK) + } + + // Check the response body is what we expect + expected := "OK\n" + if rr.Body.String() != expected { + t.Errorf("handler returned unexpected body: got %v want %v", + rr.Body.String(), expected) + } +}