chore: initialize containerized Go learning workbook (2026 DevOps/SRE)

This commit is contained in:
soda64 committed 2026-11-30 23:03:31 +01:00
commit 84be3e5d77
64 files changed
+1382

No files matched your search

+12
View File
@@ -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
```
+17
View File
@@ -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)
}
}
+10
View File
@@ -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
```
+11
View File
@@ -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)
}
}