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,8 @@
|
||||
*.exe
|
||||
*.test
|
||||
*.out
|
||||
coverage.txt
|
||||
.DS_Store
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
@@ -0,0 +1,36 @@
|
||||
# AGENTS.md — Instrukcje dla agentów AI (Go Learning Workbook — Era 2026)
|
||||
|
||||
Ten projekt to **zeszyt ćwiczeń do nauki Go dla inżyniera DevOps / Senior SRE / Platform Engineera w 2026 roku**.
|
||||
|
||||
---
|
||||
|
||||
## 1. Trzy tryby pracy agenta
|
||||
|
||||
### A. `exercises/01-core/` — Tryb Sokratejski (Rdzeń języka)
|
||||
* **Nie rozwiązuj zadań za użytkownika domyślnie.**
|
||||
* Stosuj stopniowane podpowiedzi:
|
||||
1. **Naprowadzenie:** wyjaśnij błąd kompilacji, `go vet` lub wynik `go test -race`, wskaż właściwy idiom Go.
|
||||
2. **Analogiczny przykład:** pokaż krótki przykład na *innym* problemie.
|
||||
3. **Pełne rozwiązanie:** wyłącznie na wyraźną prośbę użytkownika.
|
||||
* Po przejściu testów zaproponuj krótkie **code review** (idiomatyczność Go, obsługa błędów, brak zbędnych alokacji, `staticcheck`).
|
||||
|
||||
### B. `exercises/02-engineering-2026/` — Tryb Specyfikacja → Audyt / Review (Era AI)
|
||||
* Ucz użytkownika wyłapywać najgroźniejsze błędy AI w Go: **data races** (`go test -race`), wycieki goroutines, brak propagacji `context.Context`, ignorowanie `err` oraz brak `defer Close()`.
|
||||
|
||||
### C. `exercises/03-ecosystems/` — Tryb Architekta Cloud Native
|
||||
* Tłumacz wzorce produkcyjne Go (biblioteka standardowa `net/http` i `log/slog`, `cobra` dla CLI, metryki Prometheusa, pętla reconcilerów Kubernetes).
|
||||
|
||||
---
|
||||
|
||||
## 2. Model A — Architektura gałęzi Git (Zasada krytyczna)
|
||||
|
||||
* **`main`:** czysty szablon (nierozwiązane zadania + `notes/` + `AGENTS.md`). **Nigdy nie commituj rozwiązań na `main`.**
|
||||
* **`attempt/<YYYY-MM>`:** gałąź robocza na rozwiązania. Przed edycją sprawdź `git branch --show-current` i ostrzeż użytkownika, jeśli jest na `main`.
|
||||
* Nowe rozdziały i wspólne notatki w `notes/` trafiają na `main`, a potem `git merge main` do `attempt/*`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Zero Host Pollution (Wyłącznie kontener Podman)
|
||||
|
||||
* Nie instaluj Go na hoście i nie uruchamiaj lokalnego `go`.
|
||||
* Używaj wyłącznie `Makefile`: `make check`, `make lint`, `make test PKG=./exercises/01-core/01-basics`, `make test`, `make test-all`, `make fmt`, `make fmt-check`.
|
||||
@@ -0,0 +1,5 @@
|
||||
FROM docker.io/library/golang:1-bookworm
|
||||
|
||||
RUN go install honnef.co/go/tools/cmd/staticcheck@latest
|
||||
|
||||
WORKDIR /workspace
|
||||
@@ -0,0 +1,56 @@
|
||||
IMAGE ?= go-learning:latest
|
||||
ENGINE ?= podman
|
||||
GO_CACHE ?= go-learning-mod-cache
|
||||
PKG ?=
|
||||
|
||||
RUN_CONTAINER = $(ENGINE) run --rm \
|
||||
-v "$(CURDIR):/workspace:Z" \
|
||||
-v "$(GO_CACHE):/go/pkg/mod" \
|
||||
-w /workspace \
|
||||
$(IMAGE)
|
||||
|
||||
.PHONY: help image check lint test test-all fmt fmt-check shell
|
||||
|
||||
help:
|
||||
@echo "Dostępne komendy:"
|
||||
@echo " make image - Zbuduj obraz kontenera Go (jednorazowo)"
|
||||
@echo " make check - Sprawdź kompilację i go vet"
|
||||
@echo " make lint - Uruchom staticcheck"
|
||||
@echo " make test PKG=./exercises/01-core/01-basics - Uruchom testy wybranego rozdziału (-race)"
|
||||
@echo " make test - Uruchom testy 01-core + 02-engineering-2026"
|
||||
@echo " make test-all - Uruchom testy całego repozytorium"
|
||||
@echo " make fmt - Sformatuj kod (gofmt)"
|
||||
@echo " make fmt-check - Sprawdź formatowanie kodu"
|
||||
@echo " make shell - Otwórz powłokę bash wewnątrz kontenera"
|
||||
|
||||
image:
|
||||
$(ENGINE) build -t $(IMAGE) -f Containerfile .
|
||||
|
||||
check:
|
||||
$(RUN_CONTAINER) go vet ./...
|
||||
|
||||
lint:
|
||||
$(RUN_CONTAINER) staticcheck ./...
|
||||
|
||||
test:
|
||||
ifdef PKG
|
||||
$(RUN_CONTAINER) go test -race -v $(PKG)
|
||||
else
|
||||
$(RUN_CONTAINER) go test -race -v ./exercises/01-core/... ./exercises/02-engineering-2026/...
|
||||
endif
|
||||
|
||||
test-all:
|
||||
$(RUN_CONTAINER) go test -race -v ./...
|
||||
|
||||
fmt:
|
||||
$(RUN_CONTAINER) gofmt -w exercises
|
||||
|
||||
fmt-check:
|
||||
$(RUN_CONTAINER) sh -c 'out=$$(gofmt -l exercises); test -z "$$out" || (echo "Unformatted files:"; echo "$$out"; exit 1)'
|
||||
|
||||
shell:
|
||||
$(ENGINE) run --rm -it \
|
||||
-v "$(CURDIR):/workspace:Z" \
|
||||
-v "$(GO_CACHE):/go/pkg/mod" \
|
||||
-w /workspace \
|
||||
$(IMAGE) bash
|
||||
@@ -0,0 +1,75 @@
|
||||
# Go Learning Workbook (2026 DevOps/SRE Edition)
|
||||
|
||||
Zeszyt ćwiczeń do nauki języka Go zaprojektowany pod **DevOps / Senior SRE / Platform Engineering w 2026 roku** — izolowane środowisko **Podman** (Zero Host Pollution), `go vet`, `staticcheck`, detektor wyścigów (`go test -race`) oraz podejście ery AI.
|
||||
|
||||
## Architektura pracy (Model A — podział na gałęzie)
|
||||
|
||||
* **`main`** — czysty szablon: nierozwiązane zadania (`exercises/`), wspólne notatki (`notes/`), `AGENTS.md`. **Nie commituj tutaj rozwiązań zadań.**
|
||||
* **`attempt/<YYYY-MM>`** — gałąź robocza dla konkretnego podejścia (np. `attempt/2026-11`).
|
||||
* **Powrót po czasie / start od nowa:**
|
||||
```bash
|
||||
git checkout main
|
||||
git checkout -b attempt/2027-01
|
||||
```
|
||||
|
||||
## Szybki start (Podman)
|
||||
|
||||
```bash
|
||||
# 1. Zbuduj lokalny obraz z Go i staticcheck (raz)
|
||||
make image
|
||||
|
||||
# 2. Sprawdź kompilację, go vet i staticcheck
|
||||
make check
|
||||
make lint
|
||||
|
||||
# 3. Uruchom testy wybranego rozdziału (z detektorem data race!)
|
||||
make test PKG=./exercises/01-core/01-basics
|
||||
make test PKG=./exercises/02-engineering-2026/01-ai-code-audit
|
||||
make test PKG=./exercises/03-ecosystems/01-cli-cobra
|
||||
|
||||
# 4. Sformatuj kod
|
||||
make fmt
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ścieżki i checklista postępów
|
||||
|
||||
### Ścieżka 1: `01-core/` — Rdzeń języka (czyste `stdlib`)
|
||||
- [ ] `01-basics` — [README](exercises/01-core/01-basics/README.md): zmienne, `if`, `switch`, `for`, funkcje z wieloma zwracanymi wartościami
|
||||
- [ ] `02-slices-maps-strings` — [README](exercises/01-core/02-slices-maps-strings/README.md): slices, mapy, `rune` vs `byte`
|
||||
- [ ] `03-structs-pointers` — [README](exercises/01-core/03-structs-pointers/README.md): struktury, wskaźniki, value vs pointer receivers
|
||||
- [ ] `04-errors-handling` — [README](exercises/01-core/04-errors-handling/README.md): `errors.Is`, `errors.As`, `fmt.Errorf("%w")`
|
||||
- [ ] `05-interfaces-composition` — [README](exercises/01-core/05-interfaces-composition/README.md): „OOP po go-owemu” — embedding i niejawne interfejsy
|
||||
- [ ] `06-generics` — [README](exercises/01-core/06-generics/README.md): generyki w Go (`[T comparable]`, constraints)
|
||||
- [ ] `07-concurrency` — [README](exercises/01-core/07-concurrency/README.md): goroutines, channels, `select`, `sync.WaitGroup`, `context`
|
||||
- [ ] `08-data-structures` — [README](exercises/01-core/08-data-structures/README.md): generyczny `Stack[T]`, `Queue[T]`, thread-safe `SafeCache[K, V]`
|
||||
- [ ] `09-design-patterns` — [README](exercises/01-core/09-design-patterns/README.md): Functional Options, DI przez małe interfejsy, Worker Pool
|
||||
- [ ] `10-crud-repository` — [README](exercises/01-core/10-crud-repository/README.md): pełny CRUD w pamięci (`TaskStore`) z `sync.RWMutex`
|
||||
|
||||
### Ścieżka 2: `02-engineering-2026/` — Dobre praktyki i umiejętności ery AI
|
||||
- [ ] `01-ai-code-audit` — [README](exercises/02-engineering-2026/01-ai-code-audit/README.md): audyt „kodu z AI” (data race, błędy, edge-case'y)
|
||||
- [ ] `02-context-and-resilience` — [README](exercises/02-engineering-2026/02-context-and-resilience/README.md): `context.Context`, timeouty, retry z anulowaniem
|
||||
- [ ] `03-cross-platform-os` — [README](exercises/02-engineering-2026/03-cross-platform-os/README.md): `path/filepath`, env vars, cross-kompilacja
|
||||
- [ ] `04-testing-best-practices` — [README](exercises/02-engineering-2026/04-testing-best-practices/README.md): table-driven tests, `t.TempDir()`, `httptest`
|
||||
|
||||
### Ścieżka 3: `03-ecosystems/` — DevOps, SRE, Cloud Native
|
||||
- [ ] `01-cli-cobra` — [README](exercises/03-ecosystems/01-cli-cobra/README.md): parsowanie argumentów CLI w `cobra`
|
||||
- [ ] `02-http-api-stdlib` — [README](exercises/03-ecosystems/02-http-api-stdlib/README.md): serwer HTTP (`net/http` Go 1.22+), JSON, middleware
|
||||
- [ ] `03-sre-health-and-metrics` — [README](exercises/03-ecosystems/03-sre-health-and-metrics/README.md): `/healthz`, `/readyz`, `log/slog`, metryki Prometheusa
|
||||
- [ ] `04-k8s-style-reconciler` — [README](exercises/03-ecosystems/04-k8s-style-reconciler/README.md): pętla uzgadniania (*reconciliation loop* jak w operatorach K8s)
|
||||
|
||||
---
|
||||
|
||||
## Notatki i Mapa Ekosystemu
|
||||
|
||||
* [Indeks notatek](notes/README.md)
|
||||
* [00 — Ściągawka Go](notes/00-cheatsheet.md)
|
||||
* [01 — Ekosystem Go i najważniejsze biblioteki dla SRE/DevOps (2026)](notes/01-go-ecosystem-2026.md)
|
||||
|
||||
## Nauka z asystentem AI (metoda sokratejska i era 2026)
|
||||
|
||||
Repozytorium zawiera plik [AGENTS.md](AGENTS.md), który konfiguruje agentów AI do pracy w **3 trybach**:
|
||||
* **Tryb Sokratejski (`01-core/`)** — stopniowane podpowiedzi zamiast gotowców + code review po przejściu testów.
|
||||
* **Tryb Specyfikacja → Audyt (`02-engineering-2026/`)** — wyłapywanie data races (`-race`), wycieków goroutines i braków w obsłudze `context.Context`.
|
||||
* **Tryb Architekta Cloud Native (`03-ecosystems/`)** — wzorce CLI (`cobra`), HTTP, observability (`slog`/Prometheus) i operatorów Kubernetes.
|
||||
@@ -0,0 +1,12 @@
|
||||
# 01 — Podstawy Go (`:=`, `if`, `switch`, `for`, multiple return values)
|
||||
|
||||
## Zadania (`basics.go`)
|
||||
1. `CelsiusToFahrenheit(c float64) float64` — $F = C \cdot 1.8 + 32$.
|
||||
2. `ClassifyScore(score int) string` — `switch` bez warunku: `0..49` -> `"fail"`, `50..74` -> `"pass"`, `75..89` -> `"good"`, `90..100` -> `"excellent"`, inaczej `"invalid"`.
|
||||
3. `SumUpTo(n int) int` — suma `1..n` włącznie (dla `<= 0` zwróć `0`).
|
||||
4. `DivMod(a, b int) (int, int, bool)` — zwróć `(iloraz, reszta, true)` lub `(0, 0, false)` przy `b == 0`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/01-core/01-basics
|
||||
```
|
||||
@@ -0,0 +1,17 @@
|
||||
package basics
|
||||
|
||||
func CelsiusToFahrenheit(c float64) float64 {
|
||||
panic("TODO: przelicz Celsjusze na Fahrenheity: c*1.8 + 32")
|
||||
}
|
||||
|
||||
func ClassifyScore(score int) string {
|
||||
panic("TODO: użyj switch do klasyfikacji 0..100 lub 'invalid'")
|
||||
}
|
||||
|
||||
func SumUpTo(n int) int {
|
||||
panic("TODO: zsumuj liczby od 1 do n włącznie")
|
||||
}
|
||||
|
||||
func DivMod(a, b int) (int, int, bool) {
|
||||
panic("TODO: zwróć (a/b, a%b, true) lub (0, 0, false) dla b == 0")
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package basics
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCelsiusToFahrenheit(t *testing.T) {
|
||||
if math.Abs(CelsiusToFahrenheit(0)-32) > 1e-9 {
|
||||
t.Fatalf("expected 32, got %v", CelsiusToFahrenheit(0))
|
||||
}
|
||||
if math.Abs(CelsiusToFahrenheit(100)-212) > 1e-9 {
|
||||
t.Fatalf("expected 212, got %v", CelsiusToFahrenheit(100))
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyScore(t *testing.T) {
|
||||
cases := []struct {
|
||||
score int
|
||||
want string
|
||||
}{
|
||||
{0, "fail"}, {50, "pass"}, {80, "good"}, {95, "excellent"}, {101, "invalid"}, {-1, "invalid"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := ClassifyScore(tc.score); got != tc.want {
|
||||
t.Errorf("ClassifyScore(%d) = %q, want %q", tc.score, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSumUpTo(t *testing.T) {
|
||||
if got := SumUpTo(0); got != 0 {
|
||||
t.Errorf("got %d, want 0", got)
|
||||
}
|
||||
if got := SumUpTo(10); got != 55 {
|
||||
t.Errorf("got %d, want 55", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDivMod(t *testing.T) {
|
||||
q, r, ok := DivMod(10, 3)
|
||||
if !ok || q != 3 || r != 1 {
|
||||
t.Fatalf("got (%d, %d, %v), want (3, 1, true)", q, r, ok)
|
||||
}
|
||||
if _, _, ok := DivMod(10, 0); ok {
|
||||
t.Fatal("expected ok=false for division by zero")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
# 02 — Slices, Mapy i Stringi (`rune` vs `byte`)
|
||||
|
||||
## Zadania (`collections.go`)
|
||||
1. `UniqueInts(nums []int) []int` — usuń duplikaty, zachowując kolejność pierwszego wystąpienia.
|
||||
2. `WordCounts(text string) map[string]int` — policz słowa (lowercase, `strings.Fields`).
|
||||
3. `ReverseRunes(s string) string` — odwróć napis poprawnie dla UTF-8 (polskie znaki/emoji -> użyj `[]rune`).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/01-core/02-slices-maps-strings
|
||||
```
|
||||
@@ -0,0 +1,13 @@
|
||||
package collections
|
||||
|
||||
func UniqueInts(nums []int) []int {
|
||||
panic("TODO: usuń duplikaty zachowując kolejność")
|
||||
}
|
||||
|
||||
func WordCounts(text string) map[string]int {
|
||||
panic("TODO: policz słowa (strings.Fields + strings.ToLower)")
|
||||
}
|
||||
|
||||
func ReverseRunes(s string) string {
|
||||
panic("TODO: odwróć napis jako []rune")
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package collections
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUniqueInts(t *testing.T) {
|
||||
got := UniqueInts([]int{3, 1, 2, 3, 1, 4})
|
||||
want := []int{3, 1, 2, 4}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWordCounts(t *testing.T) {
|
||||
got := WordCounts("Go go is fast and GO works")
|
||||
if got["go"] != 3 || got["fast"] != 1 {
|
||||
t.Fatalf("unexpected counts: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReverseRunes(t *testing.T) {
|
||||
if got := ReverseRunes("zażółć"); got != "ćłóżaz" {
|
||||
t.Fatalf("got %q, want %q", got, "ćłóżaz")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# 03 — Struktury i Wskaźniki (Value vs Pointer Receivers)
|
||||
|
||||
## Zadania (`pointers.go`)
|
||||
1. `BankAccount` z prywatnym polem `balance int`, metodami `Deposit(amount int)`, `Withdraw(amount int) bool`, `Balance() int`.
|
||||
2. `IncrementAll(nums []int, delta int)` — zmodyfikuj elementy wycinka w miejscu.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/01-core/03-structs-pointers
|
||||
```
|
||||
@@ -0,0 +1,25 @@
|
||||
package pointers
|
||||
|
||||
type BankAccount struct {
|
||||
balance int
|
||||
}
|
||||
|
||||
func NewBankAccount(initial int) *BankAccount {
|
||||
panic("TODO: zwróć &BankAccount{balance: initial}")
|
||||
}
|
||||
|
||||
func (a *BankAccount) Deposit(amount int) {
|
||||
panic("TODO: dodaj amount jeśli > 0")
|
||||
}
|
||||
|
||||
func (a *BankAccount) Withdraw(amount int) bool {
|
||||
panic("TODO: wypłać jeśli amount > 0 && a.balance >= amount")
|
||||
}
|
||||
|
||||
func (a *BankAccount) Balance() int {
|
||||
return a.balance
|
||||
}
|
||||
|
||||
func IncrementAll(nums []int, delta int) {
|
||||
panic("TODO: zwiększ każdy element nums o delta w miejscu")
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package pointers
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBankAccount(t *testing.T) {
|
||||
acc := NewBankAccount(100)
|
||||
acc.Deposit(50)
|
||||
if acc.Balance() != 150 {
|
||||
t.Fatalf("got %d, want 150", acc.Balance())
|
||||
}
|
||||
if !acc.Withdraw(40) || acc.Balance() != 110 {
|
||||
t.Fatalf("withdraw failed, balance=%d", acc.Balance())
|
||||
}
|
||||
if acc.Withdraw(500) || acc.Balance() != 110 {
|
||||
t.Fatalf("expected overdraft rejection, balance=%d", acc.Balance())
|
||||
}
|
||||
}
|
||||
|
||||
func TestIncrementAll(t *testing.T) {
|
||||
nums := []int{1, 2, 3}
|
||||
IncrementAll(nums, 10)
|
||||
if !reflect.DeepEqual(nums, []int{11, 12, 13}) {
|
||||
t.Fatalf("got %v, want [11 12 13]", nums)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
# 04 — Obsługa Błędów (`errors.Is`, `errors.As`, `%w`)
|
||||
|
||||
## Zadania (`errors_ex.go`)
|
||||
1. `ParsePort(raw string) (int, error)` — zwróć `ErrInvalidPort` (opakowany przez `%w`) lub `ErrPortOutOfRange` dla wartości spoza `1..65535`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/01-core/04-errors-handling
|
||||
```
|
||||
@@ -0,0 +1,12 @@
|
||||
package errors_ex
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrInvalidPort = errors.New("invalid port number")
|
||||
ErrPortOutOfRange = errors.New("port out of range 1..65535")
|
||||
)
|
||||
|
||||
func ParsePort(raw string) (int, error) {
|
||||
panic("TODO: sparsuj port (strconv.Atoi), zwracaj błędy rozpoznawalne przez errors.Is")
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package errors_ex
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParsePort(t *testing.T) {
|
||||
port, err := ParsePort("8080")
|
||||
if err != nil || port != 8080 {
|
||||
t.Fatalf("got (%d, %v), want (8080, nil)", port, err)
|
||||
}
|
||||
if _, err := ParsePort("0"); !errors.Is(err, ErrPortOutOfRange) {
|
||||
t.Fatalf("expected ErrPortOutOfRange, got %v", err)
|
||||
}
|
||||
if _, err := ParsePort("70000"); !errors.Is(err, ErrPortOutOfRange) {
|
||||
t.Fatalf("expected ErrPortOutOfRange, got %v", err)
|
||||
}
|
||||
if _, err := ParsePort("abc"); !errors.Is(err, ErrInvalidPort) {
|
||||
t.Fatalf("expected ErrInvalidPort, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
# 05 — Interfejsy i Kompozycja („OOP po Go-owemu”)
|
||||
|
||||
W Go **nie ma dziedziczenia klas** — jest **embedding** (kompozycja struktur) oraz **niejawne interfejsy** (typ spełnia interfejs automatycznie, jeśli ma wymagane metody).
|
||||
|
||||
## Zadania (`interfaces.go`)
|
||||
1. `EmailNotifier` i `SmsNotifier` spełniające interfejs `Notifier`.
|
||||
2. `AlertService.Broadcast(msg string) []string` — wywołuje `Format(msg)` dla każdego notifiera.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/01-core/05-interfaces-composition
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
package interfaces
|
||||
|
||||
type Notifier interface {
|
||||
Format(msg string) string
|
||||
}
|
||||
|
||||
type EmailNotifier struct {
|
||||
Address string
|
||||
}
|
||||
|
||||
func (e EmailNotifier) Format(msg string) string {
|
||||
panic("TODO: zwróć '[email] ' + msg")
|
||||
}
|
||||
|
||||
type SmsNotifier struct {
|
||||
Phone string
|
||||
}
|
||||
|
||||
func (s SmsNotifier) Format(msg string) string {
|
||||
panic("TODO: zwróć '[sms] ' + msg")
|
||||
}
|
||||
|
||||
type AlertService struct {
|
||||
Notifiers []Notifier
|
||||
}
|
||||
|
||||
func (a *AlertService) Broadcast(msg string) []string {
|
||||
panic("TODO: wywołaj Format(msg) dla każdego notifiera i zwróć wyniki")
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package interfaces
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAlertService(t *testing.T) {
|
||||
svc := AlertService{
|
||||
Notifiers: []Notifier{
|
||||
EmailNotifier{Address: "ops@example.com"},
|
||||
SmsNotifier{Phone: "+48123456789"},
|
||||
},
|
||||
}
|
||||
got := svc.Broadcast("Node down")
|
||||
want := []string{"[email] Node down", "[sms] Node down"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# 06 — Generyki w Go (`[T comparable]`, `cmp.Ordered`)
|
||||
|
||||
## Zadania (`generics.go`)
|
||||
1. `Max[T cmp.Ordered](items []T) (T, bool)` — największy element lub `(zero, false)` dla pustego wycinka.
|
||||
2. `Filter[T any](items []T, keep func(T) bool) []T` — odfiltruj elementy spełniające predykat.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/01-core/06-generics
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
package generics
|
||||
|
||||
import "cmp"
|
||||
|
||||
func Max[T cmp.Ordered](items []T) (T, bool) {
|
||||
panic("TODO: znajdź największy element lub zwróć (zero, false)")
|
||||
}
|
||||
|
||||
func Filter[T any](items []T, keep func(T) bool) []T {
|
||||
panic("TODO: zwróć wycinek z elementami spełniającymi keep(item)")
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package generics
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMax(t *testing.T) {
|
||||
if _, ok := Max([]int{}); ok {
|
||||
t.Fatal("expected false for empty slice")
|
||||
}
|
||||
if got, ok := Max([]int{3, 9, 1, 7}); !ok || got != 9 {
|
||||
t.Fatalf("got (%d, %v), want (9, true)", got, ok)
|
||||
}
|
||||
if got, ok := Max([]string{"a", "z", "m"}); !ok || got != "z" {
|
||||
t.Fatalf("got (%q, %v), want (z, true)", got, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilter(t *testing.T) {
|
||||
got := Filter([]int{1, 2, 3, 4, 5}, func(n int) bool { return n%2 == 0 })
|
||||
if !reflect.DeepEqual(got, []int{2, 4}) {
|
||||
t.Fatalf("got %v, want [2 4]", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# 07 — Współbieżność (`goroutines`, `channels`, `sync.WaitGroup`, `context`)
|
||||
|
||||
## Zadania (`concurrency.go`)
|
||||
1. `ParallelSum(chunks [][]int) int` — policz sumę każdego kawałka równolegle w goroutines (użyj kanału lub `sync.WaitGroup` + `sync/atomic` / mutex) i zwróć łączną sumę.
|
||||
2. `WaitOrCancel(ctx context.Context, ch <-chan string) (string, error)` — użyj `select` na `ch` i `ctx.Done()`.
|
||||
|
||||
## Uruchomienie testów (z `-race`!)
|
||||
```bash
|
||||
make test PKG=./exercises/01-core/07-concurrency
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
package concurrency
|
||||
|
||||
import "context"
|
||||
|
||||
func ParallelSum(chunks [][]int) int {
|
||||
panic("TODO: policz sumę każdego chunka w osobnej goroutine i zsumuj wyniki bezpiecznie")
|
||||
}
|
||||
|
||||
func WaitOrCancel(ctx context.Context, ch <-chan string) (string, error) {
|
||||
panic("TODO: użyj select na <-ch oraz <-ctx.Done()")
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package concurrency
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestParallelSum(t *testing.T) {
|
||||
chunks := [][]int{{1, 2, 3}, {4, 5}, {10, 20, 30}}
|
||||
if got := ParallelSum(chunks); got != 75 {
|
||||
t.Fatalf("got %d, want 75", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitOrCancel(t *testing.T) {
|
||||
ch := make(chan string, 1)
|
||||
ch <- "ready"
|
||||
got, err := WaitOrCancel(context.Background(), ch)
|
||||
if err != nil || got != "ready" {
|
||||
t.Fatalf("got (%q, %v), want (ready, nil)", got, err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
|
||||
defer cancel()
|
||||
never := make(chan string)
|
||||
if _, err := WaitOrCancel(ctx, never); err == nil {
|
||||
t.Fatal("expected context deadline error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# 08 — Struktury Danych (`Stack[T]`, `SafeCache[K, V]`)
|
||||
|
||||
## Zadania (`ds.go`)
|
||||
1. `Stack[T]` — generyczny stos (`Push`, `Pop`, `Len`).
|
||||
2. `SafeCache[K comparable, V any]` — thread-safe cache z `sync.RWMutex` (`Set`, `Get`, `Delete`).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/01-core/08-data-structures
|
||||
```
|
||||
@@ -0,0 +1,41 @@
|
||||
package ds
|
||||
|
||||
import "sync"
|
||||
|
||||
type Stack[T any] struct {
|
||||
items []T
|
||||
}
|
||||
|
||||
func (s *Stack[T]) Push(v T) {
|
||||
panic("TODO: dodaj v na wierzch stosu")
|
||||
}
|
||||
|
||||
func (s *Stack[T]) Pop() (T, bool) {
|
||||
panic("TODO: zdejmij element lub zwróć (zero, false)")
|
||||
}
|
||||
|
||||
func (s *Stack[T]) Len() int {
|
||||
return len(s.items)
|
||||
}
|
||||
|
||||
type SafeCache[K comparable, V any] struct {
|
||||
//lint:ignore U1000 używane po zaimplementowaniu metod
|
||||
mu sync.RWMutex
|
||||
data map[K]V
|
||||
}
|
||||
|
||||
func NewSafeCache[K comparable, V any]() *SafeCache[K, V] {
|
||||
return &SafeCache[K, V]{data: make(map[K]V)}
|
||||
}
|
||||
|
||||
func (c *SafeCache[K, V]) Set(k K, v V) {
|
||||
panic("TODO: użyj c.mu.Lock() + defer c.mu.Unlock()")
|
||||
}
|
||||
|
||||
func (c *SafeCache[K, V]) Get(k K) (V, bool) {
|
||||
panic("TODO: użyj c.mu.RLock() + defer c.mu.RUnlock()")
|
||||
}
|
||||
|
||||
func (c *SafeCache[K, V]) Delete(k K) {
|
||||
panic("TODO: usuń klucz pod c.mu.Lock()")
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package ds
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStack(t *testing.T) {
|
||||
var s Stack[int]
|
||||
s.Push(10)
|
||||
s.Push(20)
|
||||
if v, ok := s.Pop(); !ok || v != 20 {
|
||||
t.Fatalf("got (%d, %v), want (20, true)", v, ok)
|
||||
}
|
||||
if v, ok := s.Pop(); !ok || v != 10 {
|
||||
t.Fatalf("got (%d, %v), want (10, true)", v, ok)
|
||||
}
|
||||
if _, ok := s.Pop(); ok {
|
||||
t.Fatal("expected empty stack")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeCacheConcurrent(t *testing.T) {
|
||||
cache := NewSafeCache[int, int]()
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 20; i++ {
|
||||
wg.Add(1)
|
||||
go func(n int) {
|
||||
defer wg.Done()
|
||||
cache.Set(n, n*2)
|
||||
_, _ = cache.Get(n)
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
if v, ok := cache.Get(5); !ok || v != 10 {
|
||||
t.Fatalf("got (%d, %v), want (10, true)", v, ok)
|
||||
}
|
||||
cache.Delete(5)
|
||||
if _, ok := cache.Get(5); ok {
|
||||
t.Fatal("expected key 5 deleted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# 09 — Wzorce Projektowe w Go (Functional Options, Worker Pool)
|
||||
|
||||
## Zadania (`patterns.go`)
|
||||
1. `NewClient(opts ...Option) Client` — wzorzec **Functional Options** (`WithTimeout`, `WithRetries`, domyślne wartości `5s` i `3`).
|
||||
2. `RunWorkerPool(workers int, jobs []int, fn func(int) int) []int` — przetwórz `jobs` przez `workers` goroutines i zwróć wyniki (w dowolnej lub tej samej kolejności — test sprawdza sumę wyników).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/01-core/09-design-patterns
|
||||
```
|
||||
@@ -0,0 +1,26 @@
|
||||
package patterns
|
||||
|
||||
import "time"
|
||||
|
||||
type Client struct {
|
||||
Timeout time.Duration
|
||||
Retries int
|
||||
}
|
||||
|
||||
type Option func(*Client)
|
||||
|
||||
func WithTimeout(d time.Duration) Option {
|
||||
panic("TODO: zwróć Option ustawiającą c.Timeout = d")
|
||||
}
|
||||
|
||||
func WithRetries(n int) Option {
|
||||
panic("TODO: zwróć Option ustawiającą c.Retries = n")
|
||||
}
|
||||
|
||||
func NewClient(opts ...Option) Client {
|
||||
panic("TODO: utwórz Client{Timeout: 5 * time.Second, Retries: 3} i zastosuj opts")
|
||||
}
|
||||
|
||||
func RunWorkerPool(workers int, jobs []int, fn func(int) int) []int {
|
||||
panic("TODO: uruchom workers goroutines pobierających zadania z kanału")
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package patterns
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFunctionalOptions(t *testing.T) {
|
||||
c := NewClient(WithTimeout(2*time.Second), WithRetries(5))
|
||||
if c.Timeout != 2*time.Second || c.Retries != 5 {
|
||||
t.Fatalf("unexpected client: %+v", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerPool(t *testing.T) {
|
||||
results := RunWorkerPool(3, []int{1, 2, 3, 4, 5}, func(x int) int { return x * 10 })
|
||||
if len(results) != 5 {
|
||||
t.Fatalf("expected 5 results, got %d", len(results))
|
||||
}
|
||||
sum := 0
|
||||
for _, r := range results {
|
||||
sum += r
|
||||
}
|
||||
if sum != 150 {
|
||||
t.Fatalf("got sum %d, want 150", sum)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
# 10 — CRUD w pamięci (`TaskStore` z `sync.RWMutex`)
|
||||
|
||||
## Zadania (`crud.go`)
|
||||
Zaimplementuj thread-safe `TaskStore`: `Create`, `Get`, `List`, `MarkDone`, `Delete` z błędami `ErrInvalidTitle` i `ErrNotFound`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/01-core/10-crud-repository
|
||||
```
|
||||
@@ -0,0 +1,51 @@
|
||||
package crud
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidTitle = errors.New("title cannot be empty")
|
||||
ErrNotFound = errors.New("task not found")
|
||||
)
|
||||
|
||||
type Task struct {
|
||||
ID uint64
|
||||
Title string
|
||||
Done bool
|
||||
}
|
||||
|
||||
type TaskStore struct {
|
||||
//lint:ignore U1000 używane po zaimplementowaniu metod
|
||||
mu sync.RWMutex
|
||||
nextID uint64
|
||||
tasks map[uint64]Task
|
||||
}
|
||||
|
||||
func NewTaskStore() *TaskStore {
|
||||
return &TaskStore{
|
||||
nextID: 1,
|
||||
tasks: make(map[uint64]Task),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TaskStore) Create(title string) (Task, error) {
|
||||
panic("TODO: zwaliduj tytuł, zapisz z auto-ID pod s.mu.Lock()")
|
||||
}
|
||||
|
||||
func (s *TaskStore) Get(id uint64) (Task, error) {
|
||||
panic("TODO: zwróć Task lub ErrNotFound pod s.mu.RLock()")
|
||||
}
|
||||
|
||||
func (s *TaskStore) List() []Task {
|
||||
panic("TODO: zwróć wszystkie zadania posortowane po ID")
|
||||
}
|
||||
|
||||
func (s *TaskStore) MarkDone(id uint64) (Task, error) {
|
||||
panic("TODO: ustaw Done = true lub zwróć ErrNotFound")
|
||||
}
|
||||
|
||||
func (s *TaskStore) Delete(id uint64) error {
|
||||
panic("TODO: usuń zadanie lub zwróć ErrNotFound")
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package crud
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTaskStoreCRUD(t *testing.T) {
|
||||
store := NewTaskStore()
|
||||
if _, err := store.Create(" "); !errors.Is(err, ErrInvalidTitle) {
|
||||
t.Fatalf("expected ErrInvalidTitle, got %v", err)
|
||||
}
|
||||
t1, err := store.Create("Learn Go")
|
||||
if err != nil || t1.ID != 1 {
|
||||
t.Fatalf("create failed: %+v, %v", t1, err)
|
||||
}
|
||||
_, _ = store.Create("Write K8s operator")
|
||||
if len(store.List()) != 2 {
|
||||
t.Fatalf("expected 2 tasks, got %d", len(store.List()))
|
||||
}
|
||||
done, err := store.MarkDone(1)
|
||||
if err != nil || !done.Done {
|
||||
t.Fatalf("mark done failed: %+v, %v", done, err)
|
||||
}
|
||||
if err := store.Delete(2); err != nil {
|
||||
t.Fatalf("delete failed: %v", err)
|
||||
}
|
||||
if err := store.Delete(2); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
# 01 — Audyt i Refaktoryzacja Kodu AI (Data Race + Edge Cases)
|
||||
|
||||
W `audit.go` znajduje się „działający” kod w stylu szybkiego draftu z AI, który:
|
||||
* ma **data race** wykrywany przez `go test -race` (równoległy zapis do licznika bez synchronizacji),
|
||||
* panikuje na pustym wycinku lub źle sformatowanym nagłówku `Bearer`.
|
||||
|
||||
## Twoje zadanie
|
||||
Napraw kod w `audit.go`, aż `make test PKG=./exercises/02-engineering-2026/01-ai-code-audit` przejdzie czysto pod `-race`.
|
||||
@@ -0,0 +1,22 @@
|
||||
package audit
|
||||
|
||||
import "strings"
|
||||
|
||||
// BUG: brak synchronizacji (sync.Mutex lub atomic.Int64) -> data race pod `go test -race`!
|
||||
type Counter struct {
|
||||
value int64
|
||||
}
|
||||
|
||||
func (c *Counter) Inc() {
|
||||
c.value++
|
||||
}
|
||||
|
||||
func (c *Counter) Value() int64 {
|
||||
return c.value
|
||||
}
|
||||
|
||||
// BUG: panikuje gdy brak spacji, nie sprawdza prefiksu "Bearer ", przepuszcza pusty token!
|
||||
func ExtractBearerToken(header string) (string, bool) {
|
||||
parts := strings.Split(header, " ")
|
||||
return parts[1], true
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCounterNoDataRace(t *testing.T) {
|
||||
var c Counter
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 50; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
c.Inc()
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if c.Value() != 50 {
|
||||
t.Fatalf("got %d, want 50", c.Value())
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractBearerToken(t *testing.T) {
|
||||
if tok, ok := ExtractBearerToken("Bearer secret123"); !ok || tok != "secret123" {
|
||||
t.Fatalf("got (%q, %v), want (secret123, true)", tok, ok)
|
||||
}
|
||||
for _, bad := range []string{"Bearer ", "Basic abc", "Malformed", ""} {
|
||||
if _, ok := ExtractBearerToken(bad); ok {
|
||||
t.Errorf("expected ok=false for %q", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
# 02 — `context.Context` i Odporność (Retry + Anulowanie)
|
||||
|
||||
## Zadania (`resilience.go`)
|
||||
1. `RetryWithContext(ctx context.Context, attempts int, delay time.Duration, fn func(context.Context) error) error` — ponawiaj `fn(ctx)` do `attempts` razy, czekając `delay` (z przerwaniem przez `ctx.Done()` w `select`).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/02-engineering-2026/02-context-and-resilience
|
||||
```
|
||||
@@ -0,0 +1,15 @@
|
||||
package resilience
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
func RetryWithContext(
|
||||
ctx context.Context,
|
||||
attempts int,
|
||||
delay time.Duration,
|
||||
fn func(context.Context) error,
|
||||
) error {
|
||||
panic("TODO: ponawiaj fn(ctx) do attempts razy, respektując ctx.Done() podczas czekania delay")
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package resilience
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRetrySucceedsOnThirdAttempt(t *testing.T) {
|
||||
calls := 0
|
||||
err := RetryWithContext(context.Background(), 3, time.Millisecond, func(ctx context.Context) error {
|
||||
calls++
|
||||
if calls < 3 {
|
||||
return errors.New("transient")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil || calls != 3 {
|
||||
t.Fatalf("got err=%v calls=%d, want nil and 3", err, calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryStopsOnContextCancel(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Millisecond)
|
||||
defer cancel()
|
||||
err := RetryWithContext(ctx, 10, 50*time.Millisecond, func(ctx context.Context) error {
|
||||
return errors.New("always fails")
|
||||
})
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("expected context.DeadlineExceeded, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# 03 — Programowanie Cross-Platform (`path/filepath`, env vars, `runtime.GOOS`)
|
||||
|
||||
## Zadania (`crossos.go`)
|
||||
1. `ConfigPath(baseDir, appName string) string` — użyj `filepath.Join(baseDir, appName, "config.yaml")`.
|
||||
2. `EnvOrDefault(lookup func(string) (string, bool), key, fallback string) string` — pobierz zmienną ze wstrzykniętej funkcji `lookup` (np. `os.LookupEnv`) lub zwróć `fallback` gdy brak lub pusta.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/02-engineering-2026/03-cross-platform-os
|
||||
```
|
||||
@@ -0,0 +1,9 @@
|
||||
package crossos
|
||||
|
||||
func ConfigPath(baseDir, appName string) string {
|
||||
panic("TODO: użyj filepath.Join(baseDir, appName, \"config.yaml\")")
|
||||
}
|
||||
|
||||
func EnvOrDefault(lookup func(string) (string, bool), key, fallback string) string {
|
||||
panic("TODO: wywołaj lookup(key); jeśli brak lub puste po TrimSpace -> fallback")
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package crossos
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestConfigPath(t *testing.T) {
|
||||
base := filepath.Join("home", "ops")
|
||||
got := ConfigPath(base, "monitor")
|
||||
want := filepath.Join(base, "monitor", "config.yaml")
|
||||
if got != want {
|
||||
t.Fatalf("got %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvOrDefault(t *testing.T) {
|
||||
env := map[string]string{"LOG_LEVEL": "debug", "EMPTY": " "}
|
||||
lookup := func(k string) (string, bool) { v, ok := env[k]; return v, ok }
|
||||
|
||||
if got := EnvOrDefault(lookup, "LOG_LEVEL", "info"); got != "debug" {
|
||||
t.Fatalf("got %q, want debug", got)
|
||||
}
|
||||
if got := EnvOrDefault(lookup, "EMPTY", "info"); got != "info" {
|
||||
t.Fatalf("got %q, want info", got)
|
||||
}
|
||||
if got := EnvOrDefault(lookup, "MISSING", "info"); got != "info" {
|
||||
t.Fatalf("got %q, want info", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# 04 — Dobre Praktyki Testowania (`t.TempDir()`, In-Memory Fakes)
|
||||
|
||||
## Zadania (`testing_ex.go`)
|
||||
1. `WriteAndReadLines(path string, lines []string) ([]string, error)` — zapisz linie do pliku i odczytaj je z powrotem.
|
||||
2. `FeatureFlags.IsEnabled(name string) bool` — korzysta z małego interfejsu `Store` (łatwego do testowania z In-Memory Fake bez mocków).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=./exercises/02-engineering-2026/04-testing-best-practices
|
||||
```
|
||||
@@ -0,0 +1,17 @@
|
||||
package testing_ex
|
||||
|
||||
type Store interface {
|
||||
Get(key string) (string, bool)
|
||||
}
|
||||
|
||||
type FeatureFlags struct {
|
||||
Store Store
|
||||
}
|
||||
|
||||
func (f FeatureFlags) IsEnabled(name string) bool {
|
||||
panic("TODO: pobierz z f.Store.Get(name); zwróć true dla 'true' lub '1' (case-insensitive)")
|
||||
}
|
||||
|
||||
func WriteAndReadLines(path string, lines []string) ([]string, error) {
|
||||
panic("TODO: zapisz lines (os.WriteFile) i odczytaj z powrotem (os.ReadFile)")
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package testing_ex
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeStore map[string]string
|
||||
|
||||
func (f fakeStore) Get(key string) (string, bool) { v, ok := f[key]; return v, ok }
|
||||
|
||||
func TestFeatureFlagsTableDriven(t *testing.T) {
|
||||
flags := FeatureFlags{Store: fakeStore{"a": "true", "b": "1", "c": "false"}}
|
||||
cases := []struct {
|
||||
name string
|
||||
want bool
|
||||
}{{"a", true}, {"b", true}, {"c", false}, {"missing", false}}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := flags.IsEnabled(tc.name); got != tc.want {
|
||||
t.Errorf("IsEnabled(%q) = %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteAndReadLines(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "lines.txt")
|
||||
want := []string{"alpha", "beta", "gamma"}
|
||||
got, err := WriteAndReadLines(path, want)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
module gitea.wired.synology.me/soda64/go-learning
|
||||
|
||||
go 1.24
|
||||
|
||||
require github.com/spf13/cobra v1.9.1
|
||||
|
||||
require (
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/spf13/pflag v1.0.6 // indirect
|
||||
)
|
||||
@@ -0,0 +1,10 @@
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
|
||||
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
|
||||
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
|
||||
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,14 @@
|
||||
# Ściągawka Go
|
||||
|
||||
## Złote zasady idiomatycznego Go
|
||||
* **Błędy to wartości:** zawsze sprawdzaj `if err != nil`, opakowuj kontekstem przez `fmt.Errorf("doing x: %w", err)`, sprawdzaj przez `errors.Is` / `errors.As`.
|
||||
* **Małe interfejsy:** definiuj interfejs po stronie konsumenta, zwykle 1–2 metody (np. `io.Reader`).
|
||||
* **Zawsze zamykaj zasoby:** `defer resp.Body.Close()` lub `defer f.Close()`.
|
||||
* **Współbieżność:** zawsze używaj `context.Context` do timeoutów i anulowania goroutines; zawsze testuj z `go test -race`.
|
||||
* **Zero values:** projektuj struktury tak, żeby ich wartość zerowa była od razu użyteczna.
|
||||
|
||||
## Komendy `make`
|
||||
* `make check` — `go vet ./...`
|
||||
* `make lint` — `staticcheck ./...`
|
||||
* `make test PKG=./exercises/01-core/01-basics` — testy jednego rozdziału z `-race`
|
||||
* `make fmt` — `gofmt -w exercises`
|
||||
@@ -0,0 +1,14 @@
|
||||
# Ekosystem Go i najważniejsze biblioteki dla SRE/DevOps (2026)
|
||||
|
||||
Go słynie z **potężnej biblioteki standardowej (`stdlib`)** — w wielu przypadkach nie potrzebujesz zewnętrznego frameworka.
|
||||
|
||||
| Obszar | Standard (2026) | Do czego służy |
|
||||
| :--- | :--- | :--- |
|
||||
| **HTTP Server & Client** | `net/http` (stdlib, routing Go 1.22+) / `chi` | Nowoczesne serwisy HTTP i REST API bez ciężkiego frameworka. |
|
||||
| **Strukturalne logowanie** | `log/slog` (stdlib) | Wbudowane logi JSON/tekstowe z kontekstem i atrybutami. |
|
||||
| **CLI** | `github.com/spf13/cobra` | Standard w `kubectl`, `docker`, `gh`, `tea`, `helm`. |
|
||||
| **Kubernetes / Operatory** | `k8s.io/client-go`, `controller-runtime` (`kubebuilder`) | Rozmawianie z API K8s i pisanie własnych operatorów/kontrolerów. |
|
||||
| **Observability / Metryki** | `prometheus/client_golang`, `go.opentelemetry.io/otel` | Metryki Prometheusa i distributed tracing (OpenTelemetry). |
|
||||
| **Bazy danych (SQL)** | `database/sql`, `pgx`, `sqlc` | Bezpieczne zapytania SQL (`sqlc` generuje typowany kod Go ze zwykłego SQL). |
|
||||
| **Konfiguracja** | `caarlos0/env`, `spf13/viper` | Parsowanie zmiennych środowiskowych i plików YAML/TOML. |
|
||||
| **Linting i jakość** | `go vet`, `staticcheck`, `golangci-lint`, `go test -race` | Wykrywanie błędów, nieidiomatycznego kodu i wyścigów pamięci. |
|
||||
@@ -0,0 +1,4 @@
|
||||
# Notatki z nauki Go
|
||||
|
||||
* [00 — Ściągawka Go](00-cheatsheet.md)
|
||||
* [01 — Ekosystem Go i najważniejsze biblioteki dla SRE/DevOps (2026)](01-go-ecosystem-2026.md)
|
||||
Reference in new issue
Block a user