Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
go-sample-app
hello_server

2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
2 changes: 1 addition & 1 deletion go.sum
Original file line number Diff line number Diff line change
@@ -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=

7 changes: 7 additions & 0 deletions hello_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -31,6 +37,7 @@ func main() {
r := mux.NewRouter()

r.HandleFunc("/", handler)
r.HandleFunc("/healthz", healthzHandler)

srv := &http.Server{
Handler: r,
Expand Down
28 changes: 27 additions & 1 deletion hello_server_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main
import (

"net/http"
"net/http/httptest"
"time"
"testing"
)
Expand Down Expand Up @@ -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)
}
}