Skip to content

Objective 1: Identify and correct errors in the HealthCheck function #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
30 changes: 20 additions & 10 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,25 +46,35 @@ func main() {

// HealthCheck report if a list of web service is up and running.
func HealthCheck(urls []string) []Result {
results := make([]Result, 0, len(urls))
results := make([]Result, len(urls))

var wg sync.WaitGroup
wg.Add(len(urls))
for _, url := range urls {
go func() {
for i, url := range urls {
// Pass a copy of `i` and `url` to avoid loop variable capture issue for Go 1.21 and below.
// (unnecessary for Go 1.22+: https://go.dev/blog/loopvar-preview)
go func(i int, url string) {
defer wg.Done()
var result Result
start := time.Now()
resp, err := http.Get(url)

// Instead of append, use `i` to assign to specific index of `results` to avoid data race.
// Use direct index writes instead of mutex to preserve same order as the `urls` slice input.
if err != nil {
result.Err = err
results[i] = Result{Err: err}
} else {
result.Status = resp.StatusCode
result.Url = url
result.Latency = time.Since(start)
results[i] = Result{
Status: resp.StatusCode,
Url: url,
Latency: time.Since(start),
}

// Close the response body as recommended in the http.Get documentation.
defer resp.Body.Close()
// We don't need to read the body, so we drain up to 4KB of it to ensure connection reuse.
io.CopyN(io.Discard, resp.Body, 4096)
}
results = append(results, result)
}()
}(i, url)
}

wg.Wait()
Expand Down
55 changes: 53 additions & 2 deletions main_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package main

import (
"golang.org/x/exp/slices"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"

"golang.org/x/exp/slices"
)

var services = `https://stackoverflow.com
Expand All @@ -15,7 +19,54 @@ https://www.finconsgroup.com
`

func TestHealthCheck(t *testing.T) {
panic("TODO implements me")
var urls []string
statusCodes := []int{http.StatusOK, http.StatusPermanentRedirect, http.StatusNotFound, http.StatusInternalServerError}

// Create a mock server for each status code
for _, statusCode := range statusCodes {
status := statusCode
latency := time.Duration(status) * time.Millisecond

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(latency)
w.WriteHeader(status)
}))
t.Cleanup(server.Close)

// Add each mock server URL to the list of URLs
urls = append(urls, server.URL)
}

// Add an invalid URL test case
urls = append(urls, "http:/invalid-url")

results := HealthCheck(urls)

if len(results) != len(urls) {
t.Errorf("want: %d results, got %d results", len(urls), len(results))
}
for i, result := range results {
// Check the last invalid URL
if i == len(results)-1 {
if result.Err == nil {
t.Errorf("[URL index %d] want: non-nil error, got: error <nil>", i)
}
continue
}

// Check the other valid URLs
expectedStatus := statusCodes[i]
expectedLatency := time.Duration(expectedStatus) * time.Millisecond
if result.Err != nil {
t.Errorf("[URL index %d][err] want: <nil>, got: %v", i, result.Err)
}
if result.Status != expectedStatus {
t.Errorf("[URL index %d][status] want: %v, got: %v", i, expectedStatus, result.Status)
}
if result.Latency < expectedLatency {
t.Errorf("[URL index %d][latency] want: >= %v, got: %v", i, expectedLatency, result.Latency)
}
}
}

func TestGetServices(t *testing.T) {
Expand Down