chore: initialize containerized Go learning workbook (2026 DevOps/SRE)
This commit is contained in:
commit
84be3e5d77
64 files changed
+1382
No files matched your search
@@ -0,0 +1,13 @@
|
||||
# 01 — Parsowanie argumentów CLI z `cobra`
|
||||
|
||||
`github.com/spf13/cobra` to standardowy framework CLI w świecie Cloud Native (`kubectl`, `docker`, `helm`, `gh`, `tea`).
|
||||
|
||||
## Zadania (`cli.go`)
|
||||
Zbuduj `NewRootCmd(out io.Writer) *cobra.Command` z dwiema podkomendami:
|
||||
1. `add <title> [--priority|-p 3]` — wypisuje do `out`: `add:<title>:p<priority>\n`.
|
||||
2. `done <id>` — parsuje `<id>` jako int i wypisuje `done:<id>\n` (zwraca błąd dla niepoprawnej liczby).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/03-ecosystems/01-cli-cobra
|
||||
```
|
||||
@@ -0,0 +1,18 @@
|
||||
package clicobra
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func NewRootCmd(out io.Writer) *cobra.Command {
|
||||
root := &cobra.Command{
|
||||
Use: "todoctl",
|
||||
Short: "Mini CLI do nauki Cobra",
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
}
|
||||
root.SetOut(out)
|
||||
panic("TODO: dodaj podkomendy 'add' (z flagą --priority/-p domyślnie 3) oraz 'done'")
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package clicobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCobraAddAndDone(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
cmd := NewRootCmd(&buf)
|
||||
cmd.SetArgs([]string{"add", "Check nodes", "-p", "1"})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := strings.TrimSpace(buf.String()); got != "add:Check nodes:p1" {
|
||||
t.Fatalf("got %q, want %q", got, "add:Check nodes:p1")
|
||||
}
|
||||
|
||||
buf.Reset()
|
||||
cmd2 := NewRootCmd(&buf)
|
||||
cmd2.SetArgs([]string{"done", "42"})
|
||||
if err := cmd2.Execute(); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := strings.TrimSpace(buf.String()); got != "done:42" {
|
||||
t.Fatalf("got %q, want %q", got, "done:42")
|
||||
}
|
||||
|
||||
cmdBad := NewRootCmd(&buf)
|
||||
cmdBad.SetArgs([]string{"done", "not-a-number"})
|
||||
if err := cmdBad.Execute(); err == nil {
|
||||
t.Fatal("expected error for invalid id")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
# 02 — Nowoczesny Serwer HTTP (`net/http` Go 1.22+, JSON, Middleware)
|
||||
|
||||
Od Go 1.22 standardowy `http.ServeMux` wspiera metody i parametry ścieżki (`GET /items/{id}`) — często nie potrzebujesz zewnętrznego frameworka!
|
||||
|
||||
## Zadania (`server.go`)
|
||||
Zbuduj `NewHandler() http.Handler`:
|
||||
1. `GET /health` -> `200 OK`, `Content-Type: application/json`, `{"status":"ok"}`.
|
||||
2. `POST /echo` -> przyjmuje `{"message":"..."}`; odrzuca pusty `message` kodem `400`, inaczej zwraca `{"echoed":"...","len":N}`.
|
||||
3. Middleware dodający nagłówek `X-Service: go-learning`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/03-ecosystems/02-http-api-stdlib
|
||||
```
|
||||
@@ -0,0 +1,20 @@
|
||||
package httpapi
|
||||
|
||||
import "net/http"
|
||||
|
||||
type HealthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type EchoRequest struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type EchoResponse struct {
|
||||
Echoed string `json:"echoed"`
|
||||
Len int `json:"len"`
|
||||
}
|
||||
|
||||
func NewHandler() http.Handler {
|
||||
panic("TODO: zarejestruj 'GET /health' i 'POST /echo' w http.NewServeMux() oraz dodaj middleware X-Service")
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHealthAndEcho(t *testing.T) {
|
||||
h := NewHandler()
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/health", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
if rec.Header().Get("X-Service") != "go-learning" {
|
||||
t.Fatalf("missing X-Service header")
|
||||
}
|
||||
|
||||
rec2 := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/echo", strings.NewReader(`{"message":"sre"}`))
|
||||
h.ServeHTTP(rec2, req)
|
||||
if rec2.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec2.Code)
|
||||
}
|
||||
var out EchoResponse
|
||||
if err := json.NewDecoder(rec2.Body).Decode(&out); err != nil {
|
||||
t.Fatalf("decode failed: %v", err)
|
||||
}
|
||||
if out.Echoed != "sre" || out.Len != 3 {
|
||||
t.Fatalf("unexpected body: %+v", out)
|
||||
}
|
||||
|
||||
recBad := httptest.NewRecorder()
|
||||
h.ServeHTTP(recBad, httptest.NewRequest(http.MethodPost, "/echo", strings.NewReader(`{"message":" "}`)))
|
||||
if recBad.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", recBad.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# 03 — SRE Observability (`/healthz`, `/readyz`, `log/slog`, Prometheus metrics)
|
||||
|
||||
## Zadania (`observability.go`)
|
||||
1. `FormatPrometheusCounter(name, help string, value uint64) string` — wygeneruj poprawny tekst w formacie Prometheus exposition (`# HELP ...`, `# TYPE ... counter`, `<name> <value>\n`).
|
||||
2. `ReadinessHandler(ready *atomic.Bool) http.HandlerFunc` — zwróć `200 OK` gdy `ready.Load()` jest `true`, inaczej `503 Service Unavailable`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/03-ecosystems/03-sre-health-and-metrics
|
||||
```
|
||||
@@ -0,0 +1,14 @@
|
||||
package observability
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
func FormatPrometheusCounter(name, help string, value uint64) string {
|
||||
panic("TODO: zwróć format Prometheus (# HELP, # TYPE counter, name value)")
|
||||
}
|
||||
|
||||
func ReadinessHandler(ready *atomic.Bool) http.HandlerFunc {
|
||||
panic("TODO: zwróć 200 OK gdy ready.Load() == true, inaczej 503 Service Unavailable")
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package observability
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFormatPrometheusCounter(t *testing.T) {
|
||||
out := FormatPrometheusCounter("http_requests_total", "Total HTTP requests", 42)
|
||||
for _, want := range []string{
|
||||
"# HELP http_requests_total Total HTTP requests",
|
||||
"# TYPE http_requests_total counter",
|
||||
"http_requests_total 42",
|
||||
} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("missing %q in:\n%s", want, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadinessHandler(t *testing.T) {
|
||||
var ready atomic.Bool
|
||||
h := ReadinessHandler(&ready)
|
||||
|
||||
rec1 := httptest.NewRecorder()
|
||||
h(rec1, httptest.NewRequest(http.MethodGet, "/readyz", nil))
|
||||
if rec1.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("got %d, want 503", rec1.Code)
|
||||
}
|
||||
|
||||
ready.Store(true)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h(rec2, httptest.NewRequest(http.MethodGet, "/readyz", nil))
|
||||
if rec2.Code != http.StatusOK {
|
||||
t.Fatalf("got %d, want 200", rec2.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
# 04 — Mini-Reconciler w stylu Operatorów Kubernetes
|
||||
|
||||
Sercem każdego operatora Kubernetes jest **pętla uzgadniania (*reconciliation loop*)**:
|
||||
1. Odczytaj stan pożądany (*Desired State*) i stan aktualny (*Actual State*).
|
||||
2. Oblicz różnicę i wykonaj idempotentne akcje naprawcze (skalowanie w górę / w dół).
|
||||
3. Jeśli stan się zgadza — nie rób nic (*no-op*).
|
||||
|
||||
## Zadania (`reconciler.go`)
|
||||
Zaimplementuj `Reconcile(desired, actual int, actions Scaler) (int, error)`:
|
||||
* Gdy `actual < desired` -> wywołaj `actions.ScaleUp(desired - actual)` i zwróć `desired`.
|
||||
* Gdy `actual > desired` -> wywołaj `actions.ScaleDown(actual - desired)` i zwróć `desired`.
|
||||
* Gdy `actual == desired` -> nie wywołuj nic i zwróć `actual, nil`.
|
||||
* Gdy `desired < 0` -> zwróć błąd `ErrNegativeReplicas`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/03-ecosystems/04-k8s-style-reconciler
|
||||
```
|
||||
@@ -0,0 +1,14 @@
|
||||
package reconciler
|
||||
|
||||
import "errors"
|
||||
|
||||
var ErrNegativeReplicas = errors.New("desired replicas cannot be negative")
|
||||
|
||||
type Scaler interface {
|
||||
ScaleUp(delta int) error
|
||||
ScaleDown(delta int) error
|
||||
}
|
||||
|
||||
func Reconcile(desired, actual int, scaler Scaler) (int, error) {
|
||||
panic("TODO: obsłuż desired < 0, ScaleUp, ScaleDown oraz no-op gdy actual == desired")
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package reconciler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeScaler struct {
|
||||
up int
|
||||
down int
|
||||
}
|
||||
|
||||
func (f *fakeScaler) ScaleUp(delta int) error { f.up += delta; return nil }
|
||||
func (f *fakeScaler) ScaleDown(delta int) error { f.down += delta; return nil }
|
||||
|
||||
func TestReconcileDesiredVsActual(t *testing.T) {
|
||||
s := &fakeScaler{}
|
||||
got, err := Reconcile(5, 2, s)
|
||||
if err != nil || got != 5 || s.up != 3 || s.down != 0 {
|
||||
t.Fatalf("scale up failed: got=%d err=%v scaler=%+v", got, err, s)
|
||||
}
|
||||
|
||||
s2 := &fakeScaler{}
|
||||
got, err = Reconcile(1, 4, s2)
|
||||
if err != nil || got != 1 || s2.down != 3 || s2.up != 0 {
|
||||
t.Fatalf("scale down failed: got=%d err=%v scaler=%+v", got, err, s2)
|
||||
}
|
||||
|
||||
s3 := &fakeScaler{}
|
||||
got, err = Reconcile(3, 3, s3)
|
||||
if err != nil || got != 3 || s3.up != 0 || s3.down != 0 {
|
||||
t.Fatalf("no-op failed: got=%d err=%v scaler=%+v", got, err, s3)
|
||||
}
|
||||
|
||||
if _, err := Reconcile(-1, 2, s3); !errors.Is(err, ErrNegativeReplicas) {
|
||||
t.Fatalf("expected ErrNegativeReplicas, got %v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user