TExcelTAD
Home › Automation Scripting: Bash, Python & Go › One Task, Three Languages

One Task, Three Languages

The best way to feel the trade-offs from Bash vs Python vs Go is to write the same small tool three times. The task: given a list of endpoints with the HTTP status each should return, check them all, print one line per endpoint, and exit with status 1 if any check failed. Each version handles the same three cases: an endpoint that is fine, one that returns the wrong status, and one where nothing is listening.

Bash with curl

The shell version is real: it starts a local web server (Python's http.server) in the container, checks it with curl, and stops it on exit.

bash · try it yourself
cat > check-endpoints <<'SCRIPT'
#!/usr/bin/env bash
# check-endpoints FILE: each line is "NAME URL EXPECTED_STATUS"
set -euo pipefail
failed=0
while read -r name url expected; do
  [ -z "$name" ] || [ "${name:0:1}" = "#" ] && continue
  code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "$url" || true)
  if [ "$code" = "$expected" ]; then
    printf 'OK    %-8s %s\n' "$name" "$code"
  else
    printf 'FAIL  %-8s got %s, want %s\n' "$name" "${code:-none}" "$expected"
    failed=$((failed + 1))
  fi
done < "$1"
echo "$failed failed"
[ "$failed" -eq 0 ]
SCRIPT
chmod +x check-endpoints

mkdir -p www && echo ok > www/healthz
python3 -m http.server 8080 --bind 127.0.0.1 --directory www > server.log 2>&1 &
trap 'kill $!' EXIT
for _ in $(seq 50); do curl -s -o /dev/null 127.0.0.1:8080/healthz && break; sleep 0.1; done

cat > endpoints.txt <<'LIST'
# name   url                                expected
web      http://127.0.0.1:8080/healthz      200
admin    http://127.0.0.1:8080/admin        200
metrics  http://127.0.0.1:9100/metrics      200
LIST
./check-endpoints endpoints.txt; echo "-> status $?"
OK    web      200
FAIL  admin    got 404, want 200
FAIL  metrics  got 000, want 200
2 failed
-> status 1

Strengths: short, no dependencies beyond curl, readable top to bottom, the obvious choice for a CI step. Weaknesses: curl reports "nothing listening" as status 000, so the script cannot tell a refused connection from a timeout without parsing curl's exit code; the input format is whitespace-separated text; there is no way to unit-test the comparison logic; and it checks endpoints one at a time.

Python with a transport

The Python version reads the same list, but the HTTP call goes through a transport function, so it runs here against a fake and in production against urllib. It distinguishes connection errors from wrong statuses and could easily grow (JSON output, retries, YAML input):

python · try it yourself
from dataclasses import dataclass

@dataclass
class Result:
    name: str
    ok: bool
    detail: str

class ConnectionFailed(Exception):
    pass

def check_all(endpoints, transport):
    results = []
    for name, url, expected in endpoints:
        try:
            status = transport(url)
        except ConnectionFailed as e:
            results.append(Result(name, False, f"connection failed: {e}"))
            continue
        ok = status == expected
        results.append(Result(name, ok, str(status) if ok else f"got {status}, want {expected}"))
    return results

def parse(text):
    for line in text.splitlines():
        if line.strip() and not line.lstrip().startswith("#"):
            name, url, expected = line.split()
            yield name, url, int(expected)

def fake_transport(url):                     # stands in for the network
    routes = {"http://127.0.0.1:8080/healthz": 200, "http://127.0.0.1:8080/admin": 404}
    if url.startswith("http://127.0.0.1:9100"):
        raise ConnectionFailed("connection refused")
    return routes[url]

endpoints = """
# name   url                                expected
web      http://127.0.0.1:8080/healthz      200
admin    http://127.0.0.1:8080/admin        200
metrics  http://127.0.0.1:9100/metrics      200
"""
results = check_all(parse(endpoints), fake_transport)
for r in results:
    print(f"{'OK' if r.ok else 'FAIL':5} {r.name:8} {r.detail}")
failed = sum(not r.ok for r in results)
print(f"{failed} failed -> exit status {1 if failed else 0}")
OK    web      200
FAIL  admin    got 404, want 200
FAIL  metrics  connection failed: connection refused
2 failed -> exit status 1

The production transport is the urllib function from Calling REST APIs, adapted to return only the status:

python
import urllib.error, urllib.request

def urllib_transport(url, timeout=5):
    try:
        with urllib.request.urlopen(url, timeout=timeout) as resp:
            return resp.status
    except urllib.error.HTTPError as e:
        return e.code                              # 4xx/5xx are answers, not failures
    except (urllib.error.URLError, TimeoutError) as e:
        raise ConnectionFailed(str(getattr(e, "reason", e))) from e

Strengths: structured data, testable functions, clear error categories, a short path to JSON/YAML input and retries. Weaknesses: needs a Python on every machine that runs it, and becomes a packaging question as soon as it needs a third-party library.

Go with goroutines

The Go version checks all endpoints in parallel against real httptest servers and keeps results in input order. A closed server stands in for "nothing listening":

go · try it yourself
package main

import (
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"sync"
	"syscall"
	"time"
)

type Endpoint struct {
	Name, URL string
	Expected  int
}

type Result struct {
	Name, Detail string
	OK           bool
}

func checkAll(client *http.Client, eps []Endpoint) []Result {
	results := make([]Result, len(eps))
	var wg sync.WaitGroup
	for i, ep := range eps {
		wg.Add(1)
		go func() {
			defer wg.Done()
			resp, err := client.Get(ep.URL)
			switch {
			case errors.Is(err, syscall.ECONNREFUSED):
				results[i] = Result{ep.Name, "connection refused", false}
			case err != nil:
				results[i] = Result{ep.Name, "request failed", false}
			default:
				resp.Body.Close()
				ok := resp.StatusCode == ep.Expected
				detail := fmt.Sprint(resp.StatusCode)
				if !ok {
					detail = fmt.Sprintf("got %d, want %d", resp.StatusCode, ep.Expected)
				}
				results[i] = Result{ep.Name, detail, ok}
			}
		}()
	}
	wg.Wait()
	return results
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "ok") })
	web := httptest.NewServer(mux)
	defer web.Close()
	gone := httptest.NewServer(mux)
	gone.Close() // its port now refuses connections

	eps := []Endpoint{
		{"web", web.URL + "/healthz", 200},
		{"admin", web.URL + "/admin", 200},
		{"metrics", gone.URL + "/metrics", 200},
	}
	failed := 0
	for _, r := range checkAll(&http.Client{Timeout: 5 * time.Second}, eps) {
		status := "OK"
		if !r.OK {
			status = "FAIL"
			failed++
		}
		fmt.Printf("%-5s %-8s %s\n", status, r.Name, r.Detail)
	}
	code := 0
	if failed > 0 {
		code = 1
	}
	fmt.Printf("%d failed -> exit status %d\n", failed, code)
}
OK    web      200
FAIL  admin    got 404, want 200
FAIL  metrics  connection refused
2 failed -> exit status 1

Strengths: parallel by default, precise error types (ECONNREFUSED vs a timeout), one binary that runs anywhere. Weaknesses: the longest of the three, structs for everything, and a build step before anyone can run it.

Side by side

Bash Python Go
lines of logic ~15 ~35 ~60
dependencies at run time bash, curl python3 none
error categories via curl's exit code exceptions typed errors
testable without a network hard yes (transport) yes (httptest)
parallel with &/wait or xargs -P with a thread pool goroutines
right when it is a CI step or a one-off it grows logic, inputs, outputs it ships to many people or runs as a service

Test yourself

What does curl -w '%{http_code}' print when nothing is listening on the port?

  1. 404
  2. 500
  3. 000
  4. Nothing

Why can the Python version be tested without a network?

  1. Python has a built-in network simulator
  2. The HTTP call is a transport function passed in, so a test can pass a fake
  3. urllib works offline
  4. It does not make HTTP calls

How does the Go version keep its output in input order while checking in parallel?

  1. It sorts by response time
  2. Each goroutine writes results[i] for its own index, and the program prints after wg.Wait()
  3. Goroutines always finish in order
  4. It uses a mutex around fmt.Printf