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,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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user