系统列表
Distributed Systems in Go:生产级分布式平台 SDK 与微服务实战
专栏《分布式 Go 系统工程》配套完整代码实战工程,涵盖并发模型、消息队列适配、Saga 编排、弹性容错与可观测性等生产级模式。
README.mdSYSTEM.mdcmd/auth/main.gocmd/gateway/main.gocmd/orders/main.goconfig/grafana/datasources/datasources.yamlconfig/prometheus.yamlconfig/tempo.yamldeploy/kube/orderflow-infra.yamldocker-compose.ymlgo.modgo.suminternal/auth/handler.gointernal/auth/service.gointernal/domain/events.gointernal/inventory/handler.gointernal/inventory/service.gointernal/notifications/service.gointernal/orders/handler.gointernal/orders/service.gointernal/payment/service.gomigrations/000001_init_schema.up.sqlpkg/platform/auth/auth_test.gopkg/platform/auth/claims.gopkg/platform/auth/jwks.gopkg/platform/auth/middleware.gopkg/platform/auth/password.gopkg/platform/auth/token.gopkg/platform/cli/cli_test.gopkg/platform/cli/health.gopkg/platform/concurrency/context.gopkg/platform/concurrency/shutdown.gopkg/platform/concurrency/shutdown_test.gopkg/platform/concurrency/workerpool.gopkg/platform/concurrency/workerpool_test.gopkg/platform/config/config_test.gopkg/platform/config/loader.gopkg/platform/consistency/consistency_test.gopkg/platform/consistency/idempotency.gopkg/platform/consistency/optimistic.gopkg/platform/consistency/saga.gopkg/platform/ctxutil/context.gopkg/platform/ctxutil/context_test.gopkg/platform/ctxutil/keys.gopkg/platform/database/database_test.gopkg/platform/database/errors.gopkg/platform/database/migrate.gopkg/platform/database/pool.gopkg/platform/database/retry.gopkg/platform/database/tx.gopkg/platform/messaging/fake.gopkg/platform/messaging/fake_test.gopkg/platform/messaging/interfaces.gopkg/platform/messaging/kafka/consumer.gopkg/platform/messaging/kafka/producer.gopkg/platform/messaging/nats/publisher.gopkg/platform/messaging/nats/subscriber.gopkg/platform/messaging/schema.gopkg/platform/middleware/bodyclose.gopkg/platform/middleware/chain.gopkg/platform/middleware/cors.gopkg/platform/middleware/errors.gopkg/platform/middleware/health.gopkg/platform/middleware/logging.gopkg/platform/middleware/middleware_test.gopkg/platform/middleware/recover.gopkg/platform/middleware/requestid.gopkg/platform/middleware/timeout.gopkg/platform/observability/context.gopkg/platform/observability/logger.gopkg/platform/observability/metrics.gopkg/platform/observability/observability_test.gopkg/platform/observability/tracing.gopkg/platform/orchestration/budget.gopkg/platform/orchestration/degrade.gopkg/platform/orchestration/fanout.gopkg/platform/orchestration/orchestration_test.gopkg/platform/resilience/circuit.gopkg/platform/resilience/resilience_test.gopkg/platform/resilience/retry.gotests/live_infra_test.gotests/orderflow_integration_test.go
pkg/platform/middleware/middleware_test.go
| package middleware |
| import ( |
| "bytes" |
| "context" |
| "encoding/json" |
| "errors" |
| "net/http" |
| "net/http/httptest" |
| "testing" |
| "time" |
| ) |
| func TestChain_ExecutionOrder(t *testing.T) { |
| var order []string |
| m1 := func(next http.Handler) http.Handler { |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| order = append(order, "m1_in") |
| next.ServeHTTP(w, r) |
| order = append(order, "m1_out") |
| }) |
| } |
| m2 := func(next http.Handler) http.Handler { |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| order = append(order, "m2_in") |
| next.ServeHTTP(w, r) |
| order = append(order, "m2_out") |
| }) |
| } |
| handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| order = append(order, "handler") |
| w.WriteHeader(http.StatusOK) |
| }) |
| chained := Chain(handler, m1, m2) |
| rec := httptest.NewRecorder() |
| req := httptest.NewRequest(http.MethodGet, "/test", nil) |
| chained.ServeHTTP(rec, req) |
| expected := []string{"m1_in", "m2_in", "handler", "m2_out", "m1_out"} |
| if len(order) != len(expected) { |
| t.Fatalf("unexpected order length: got %v, expected %v", order, expected) |
| } |
| for i := range expected { |
| if order[i] != expected[i] { |
| t.Fatalf("at index %d: got %s, expected %s", i, order[i], expected[i]) |
| } |
| } |
| } |
| func TestRecover_CatchesPanic(t *testing.T) { |
| panickingHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| panic("database connection blew up") |
| }) |
| chained := Chain(panickingHandler, Recover()) |
| rec := httptest.NewRecorder() |
| req := httptest.NewRequest(http.MethodGet, "/panic", nil) |
| chained.ServeHTTP(rec, req) |
| if rec.Code != http.StatusInternalServerError { |
| t.Fatalf("expected 500 status, got %d", rec.Code) |
| } |
| var apiErr APIError |
| if err := json.Unmarshal(rec.Body.Bytes(), &apiErr); err != nil { |
| t.Fatalf("expected valid JSON error response: %v", err) |
| } |
| if apiErr.Code != "INTERNAL_ERROR" { |
| t.Fatalf("expected INTERNAL_ERROR code, got %s", apiErr.Code) |
| } |
| } |
| func TestRequestID_GeneratesAndPropagates(t *testing.T) { |
| handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| id := RequestIDFromContext(r.Context()) |
| if id == "" { |
| t.Error("expected request id in context") |
| } |
| w.WriteHeader(http.StatusOK) |
| }) |
| chained := Chain(handler, RequestID()) |
| // Case 1: auto-generate UUID |
| rec1 := httptest.NewRecorder() |
| req1 := httptest.NewRequest(http.MethodGet, "/id", nil) |
| chained.ServeHTTP(rec1, req1) |
| if rec1.Header().Get("X-Request-ID") == "" { |
| t.Fatal("expected X-Request-ID header in response") |
| } |
| // Case 2: preserve incoming ID |
| rec2 := httptest.NewRecorder() |
| req2 := httptest.NewRequest(http.MethodGet, "/id", nil) |
| req2.Header.Set("X-Request-ID", "upstream-trace-999") |
| chained.ServeHTTP(rec2, req2) |
| if rec2.Header().Get("X-Request-ID") != "upstream-trace-999" { |
| t.Fatalf("expected upstream id preserved, got %s", rec2.Header().Get("X-Request-ID")) |
| } |
| } |
| func TestTimeout_CancelsSlowHandler(t *testing.T) { |
| slowHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| select { |
| case <-r.Context().Done(): |
| return |
| case <-time.After(100 * time.Millisecond): |
| w.WriteHeader(http.StatusOK) |
| } |
| }) |
| chained := Chain(slowHandler, Recover(), Timeout(20*time.Millisecond)) |
| rec := httptest.NewRecorder() |
| req := httptest.NewRequest(http.MethodGet, "/slow", nil) |
| chained.ServeHTTP(rec, req) |
| if rec.Code != http.StatusGatewayTimeout { |
| t.Fatalf("expected 504 Gateway Timeout, got %d", rec.Code) |
| } |
| } |
| func TestDecodeJSON_Validation(t *testing.T) { |
| type RequestData struct { |
| Name string `json:"name"` |
| Age int `json:"age"` |
| } |
| // Case 1: valid payload |
| validBody := bytes.NewBufferString(`{"name":"Alice","age":30}`) |
| req1 := httptest.NewRequest(http.MethodPost, "/users", validBody) |
| req1.Header.Set("Content-Type", "application/json") |
| var data1 RequestData |
| if err := DecodeJSON(req1, &data1); err != nil { |
| t.Fatalf("failed to decode valid json: %v", err) |
| } |
| if data1.Name != "Alice" || data1.Age != 30 { |
| t.Fatalf("unexpected decoded values: %+v", data1) |
| } |
| // Case 2: unknown field rejected |
| unknownFieldBody := bytes.NewBufferString(`{"name":"Bob","age":25,"extra":"forbidden"}`) |
| req2 := httptest.NewRequest(http.MethodPost, "/users", unknownFieldBody) |
| req2.Header.Set("Content-Type", "application/json") |
| var data2 RequestData |
| if err := DecodeJSON(req2, &data2); err == nil { |
| t.Fatal("expected error on unknown field, got nil") |
| } |
| // Case 3: wrong content-type |
| req3 := httptest.NewRequest(http.MethodPost, "/users", validBody) |
| var data3 RequestData |
| if err := DecodeJSON(req3, &data3); err == nil { |
| t.Fatal("expected error on missing Content-Type application/json") |
| } |
| } |
| func TestHealthHandlers(t *testing.T) { |
| // Liveness |
| liveRec := httptest.NewRecorder() |
| liveReq := httptest.NewRequest(http.MethodGet, "/healthz", nil) |
| LivenessHandler().ServeHTTP(liveRec, liveReq) |
| if liveRec.Code != http.StatusOK { |
| t.Fatalf("expected 200 for liveness, got %d", liveRec.Code) |
| } |
| // Readiness healthy |
| readyRec := httptest.NewRecorder() |
| readyReq := httptest.NewRequest(http.MethodGet, "/ready", nil) |
| checkPass := func(ctx context.Context) error { return nil } |
| ReadinessHandler(checkPass).ServeHTTP(readyRec, readyReq) |
| if readyRec.Code != http.StatusOK { |
| t.Fatalf("expected 200 for readiness, got %d", readyRec.Code) |
| } |
| // Readiness failing dependency |
| failRec := httptest.NewRecorder() |
| failReq := httptest.NewRequest(http.MethodGet, "/ready", nil) |
| checkFail := func(ctx context.Context) error { return errors.New("database down") } |
| ReadinessHandler(checkFail).ServeHTTP(failRec, failReq) |
| if failRec.Code != http.StatusServiceUnavailable { |
| t.Fatalf("expected 503 for unhealthy dependency, got %d", failRec.Code) |
| } |
| } |