Scenario test · 90 minutes
Check a team's lab endpoints and report the result
- Build a concurrent endpoint checker with flags, a timeout and a JSON report
- Test the checker against a local server with table tests
- Report the results and the limits of the tool in a short document
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your team runs a small lab: six health endpoints on one local server (one of them, cache1, has no route yet and answers 404) and a printer in the lab network. Each morning someone opens them by hand. Your lead asks you for a tool, epcheck, that does it in one second and leaves a report. The tool reads a list of the endpoints of your OWN lab from a file, checks each one at the same time with a timeout, and writes a JSON report. It must refuse any address that is not your own machine: you check only systems that you own, and the tool must enforce that rule, not only your good will.
This test uses the whole course: modules and builds (lesson 1), structs and maps (2), errors and packages (3), files, JSON and flags (4), HTTP and contexts (5), a worker pool (6), tests (7) and a finished tool (8 and 9).
The test server is the input. Everything is fixed, so every reader gets the same answers. Make the folder and the server. The server listens on 127.0.0.1:8203 and nowhere else.
mkdir -p ~/krlab/go/epcheck/labserver
cd ~/krlab/go/epcheck
go mod init krlab/epcheckgo mod init writes this go.mod. The lab zip holds it with go 1.22, so that it builds on every Go from 1.22:
go.mod
module krlab/epcheck
go 1.22Write labserver/main.go.
epcheck/labserver/main.go
// Command labserver is the test server of the scenario. It listens on 127.0.0.1 only.
package main
import (
"log"
"net/http"
"time"
)
func main() {
mux := http.NewServeMux()
up := func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok\n")) }
mux.HandleFunc("GET /web1/health", up)
mux.HandleFunc("GET /web2/health", up)
mux.HandleFunc("GET /db1/health", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "database is down", http.StatusInternalServerError)
})
mux.HandleFunc("GET /api1/health", func(w http.ResponseWriter, r *http.Request) {
time.Sleep(300 * time.Millisecond)
up(w, r)
})
mux.HandleFunc("GET /batch1/health", func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(3 * time.Second):
up(w, r)
case <-r.Context().Done():
}
})
srv := &http.Server{Addr: "127.0.0.1:8203", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
log.Println("listening on", srv.Addr)
log.Fatal(srv.ListenAndServe())
}Write the input file endpoints.txt. One endpoint is not local: its host ends in .test, a name that is reserved for tests. Your tool must not send a request to it.
endpoints.txt
# name url
web1 http://127.0.0.1:8203/web1/health
web2 http://127.0.0.1:8203/web2/health
db1 http://127.0.0.1:8203/db1/health
cache1 http://127.0.0.1:8203/cache1/health
api1 http://127.0.0.1:8203/api1/health
batch1 http://127.0.0.1:8203/batch1/health
printer http://printer.lab.test/health- epcheck → labserver: one request for each lab endpoint
- epcheck → printer (blocked): host is not local, no request goes out
Start the server in a second terminal with go run ./labserver, and leave it running while you work. Stop it with Ctrl+C when you are done.
Your tasks
There is no code here. Use the lessons.
- The package. Make the package
checkwith a type for one endpoint and a type for one result. A result has the keysname,url,statusandresultin JSON.resultis one ofup,down,timeout,refusedorerror.refusedmeans that the tool itself did not send the request (the host is not local). A connection that the server refuses iserror. - Read the file. Write a function that reads
endpoints.txt: onename urlpair for each line, no blank lines, no lines that start with#. A line without exactly two words is an error that names the file and the line number. - Check one endpoint. Write a function that checks one endpoint with its own timeout from a context. A status from 200 to 299 is
up. Any other status isdown, and the status is kept. A request that runs out of time istimeout, with status 0. A URL whose host is not127.0.0.1,localhostor::1isrefused, with status 0, and no request is sent (the packagenet/urlreads the host: lesson 5). A redirect is not followed: a 3xx answer isdown, with its status. - Check all of them. Check all endpoints with a pool of workers. Return the results sorted by name (
sort.Slice, lesson 2). - The command. Write
main.gowith the flags-in(defaultendpoints.txt),-out(defaultreport.json),-workers(default 4) and-timeout(default one second). Write the report as indented JSON with the permission0o600. Print one summary line, such as6 checked: 2 up, 1 down, 1 timeout, 1 refused, 1 error. The five counters must add up to the total, so that no failure goes uncounted. Exit codes: 0 when all are up, 1 when the tool cannot read the input or write the report, 2 for wrong use of the command line, and 3 when at least one endpoint is not up. - The tests. Write table tests for tasks 2 and 3, and run
go vet ./...andgo test -race ./...with no complaint. For the tests of task 3 do not use the lab server. Start a test server that the test owns: the packagenet/http/httptesthashttptest.NewServer(handler), which listens on a free port on127.0.0.1and gives its address in.URL. Test an up, a missing, a broken, a slow, a redirecting and a refused endpoint (a foreign host). For the file of task 2,t.TempDir()gives a folder (lesson 7). - Run it. Build the tool, run it against the lab server, and read the report. Then run it with
-timeout 5s, and with-in missing.txt.
Check your results.
Hand in
Show three things to your lead (or to an employer, as proof of what you can do):
- The tool. The folder
~/krlab/go/epcheckwithgo.mod,main.goand the packagecheck. It builds withgo buildand has no outside dependency.gofmt -l .prints nothing. - The tests.
go vet ./...andgo test -race ./...pass. Copy the last lines of the test run into your report. - A short written report, in a file
REPORT.mdof one page, with these headings:## Summary: what the tool does and the result of the run, in three sentences.## Scope: which systems the tool checks and how it refuses the others.## How I tested it: the cases of your tests and what each one proves.## What the results show: the table of the seven endpoints and one sentence on each one that is not up.## Limits and next steps: what the tool does not do (at least three points) and what you would add first.
Review your work
Compare your tool with this model solution. A different layout is fine if it does the same and passes the same tests.
Model solution: check/check.go
// Package check tests the health endpoints of a team's own lab.
package check
import (
"bufio"
"context"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"sort"
"strings"
"sync"
"time"
)
// Endpoint is one line of the input file.
type Endpoint struct {
Name, URL string
}
// Result is one entry of the report.
type Result struct {
Name string `json:"name"`
URL string `json:"url"`
Status int `json:"status"`
Result string `json:"result"`
}
// ReadEndpoints reads "name url" lines. Blank lines and lines that start with # are skipped.
func ReadEndpoints(path string) ([]Endpoint, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
var out []Endpoint
sc := bufio.NewScanner(f)
for n := 1; sc.Scan(); n++ {
line := strings.TrimSpace(sc.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
fields := strings.Fields(line)
if len(fields) != 2 {
return nil, fmt.Errorf("%s:%d: want a name and a url", path, n)
}
out = append(out, Endpoint{fields[0], fields[1]})
}
return out, sc.Err()
}
// local reports whether a URL points at this machine. The tool checks nothing else.
func local(raw string) bool {
u, err := url.Parse(raw)
if err != nil {
return false
}
switch u.Hostname() {
case "127.0.0.1", "localhost", "::1":
return true
}
return false
}
// client does not follow a redirect: the tool must stay on this machine.
var client = &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
}}
// One checks a single endpoint. The result is up, down, timeout, refused or error.
func One(ctx context.Context, ep Endpoint, timeout time.Duration) Result {
r := Result{Name: ep.Name, URL: ep.URL}
if !local(ep.URL) {
r.Result = "refused"
return r
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ep.URL, nil)
if err != nil {
r.Result = "error"
return r
}
resp, err := client.Do(req)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
r.Result = "timeout"
} else {
r.Result = "error"
}
return r
}
defer resp.Body.Close()
r.Status = resp.StatusCode
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
r.Result = "up"
} else {
r.Result = "down"
}
return r
}
// All checks every endpoint with a pool of workers. The results are sorted by name.
func All(ctx context.Context, eps []Endpoint, workers int, timeout time.Duration) []Result {
jobs := make(chan Endpoint)
out := make(chan Result)
var wg sync.WaitGroup
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
for ep := range jobs {
out <- One(ctx, ep, timeout)
}
}()
}
go func() {
defer close(jobs)
for _, ep := range eps {
jobs <- ep
}
}()
go func() {
wg.Wait()
close(out)
}()
results := []Result{}
for r := range out {
results = append(results, r)
}
sort.Slice(results, func(i, j int) bool { return results[i].Name < results[j].Name })
return results
}Model solution: main.go
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"time"
"krlab/epcheck/check"
)
func main() {
in := flag.String("in", "endpoints.txt", "file with one name and URL per line")
out := flag.String("out", "report.json", "JSON report to write")
workers := flag.Int("workers", 4, "checks at one time")
timeout := flag.Duration("timeout", time.Second, "limit for each endpoint")
flag.Parse()
if flag.NArg() > 0 || *workers < 1 || *timeout <= 0 {
fmt.Fprintln(os.Stderr, "usage: epcheck [-in file] [-out file] [-workers n] [-timeout d]")
os.Exit(2)
}
eps, err := check.ReadEndpoints(*in)
if err != nil {
fmt.Fprintln(os.Stderr, "epcheck:", err)
os.Exit(1)
}
results := check.All(context.Background(), eps, *workers, *timeout)
data, err := json.MarshalIndent(results, "", " ")
if err == nil {
err = os.WriteFile(*out, append(data, '\n'), 0o600)
}
if err != nil {
fmt.Fprintln(os.Stderr, "epcheck:", err)
os.Exit(1)
}
count := map[string]int{}
for _, r := range results {
count[r.Result]++
}
fmt.Printf("%d checked: %d up, %d down, %d timeout, %d refused, %d error\n",
len(results), count["up"], count["down"], count["timeout"], count["refused"], count["error"])
if count["up"] != len(results) {
os.Exit(3)
}
}Model solution: check/check_test.go
package check
import (
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
)
func TestOne(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/ok", func(w http.ResponseWriter, r *http.Request) {})
mux.HandleFunc("/broken", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "no", http.StatusInternalServerError)
})
mux.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://203.0.113.7/", http.StatusFound)
})
mux.HandleFunc("/slow", func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(2 * time.Second):
case <-r.Context().Done():
}
})
srv := httptest.NewServer(mux)
defer srv.Close()
tests := []struct {
name, url, want string
status int
}{
{"ok", srv.URL + "/ok", "up", 200},
{"missing", srv.URL + "/missing", "down", 404},
{"broken", srv.URL + "/broken", "down", 500},
{"slow", srv.URL + "/slow", "timeout", 0},
{"redirect", srv.URL + "/redirect", "down", 302},
{"foreign", "http://printer.lab.test/health", "refused", 0},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := One(context.Background(), Endpoint{tc.name, tc.url}, 200*time.Millisecond)
if got.Result != tc.want || got.Status != tc.status {
t.Errorf("got %q %d, want %q %d", got.Result, got.Status, tc.want, tc.status)
}
})
}
}
func TestReadEndpoints(t *testing.T) {
dir := t.TempDir()
good := filepath.Join(dir, "good.txt")
if err := os.WriteFile(good, []byte("# c\n\nweb1 http://127.0.0.1/a\n"), 0o600); err != nil {
t.Fatal(err)
}
eps, err := ReadEndpoints(good)
if err != nil || len(eps) != 1 || eps[0].Name != "web1" {
t.Fatalf("got %v, %v", eps, err)
}
bad := filepath.Join(dir, "bad.txt")
if err := os.WriteFile(bad, []byte("web1\n"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := ReadEndpoints(bad); err == nil {
t.Error("a line without a URL gave no error")
}
}The model solution has at least these limits: a name such as localhost could be changed in the hosts file of a machine; each endpoint is checked once, so a single slow answer is reported as timeout without a retry; and the report has no time stamp, so two reports cannot be told apart by date.
Mark your report
You mark this yourself, or you ask a colleague or a mentor to mark it. The page checks the numbers above; it cannot read your report.
| Criterion | Not yet | Meets the standard | Strong |
|---|---|---|---|
| Results | A result is wrong or missing from the table. | Seven rows: 3 up, db1 500, cache1 404, batch1 timeout, printer refused; the counters of the summary line add up to 7; exit code 3. | Also explains the -timeout 5s and -in missing.txt runs. |
| Evidence | "Tests pass", with no output. | The last lines of go test -race, and the commands to re-run. | Another person rebuilds the tool and gets the same report. |
| Scope | Does not say which systems the tool may check. | Only the lab; refusal is in code (refused means the tool sent nothing: host not local; no redirects) and tested. | Names a way round the refusal, such as the hosts file. |
| Tests | Test cases have no reason. | Each case has a reason: 404 is down because the server answered. | Says which behaviour no test covers. |
| Limits | No limits, or "the tool is complete". | Three honest limits and the first one to fix. | Each next step names the lesson that shows how. |
| Writing | The summary explains code before the result. | Dated, one page; the summary gives the result first. | A lead who cannot read Go can act. |
Meets the standard in every row: you can show this report as a work sample. Remove names and data that are not yours to share.
The report shows your work on this scenario, done on your own machine without a proctor. It does not show work on a team's code base.
Last, think about the limits that you found. Which one would you fix first, and which lesson shows you how?