Add examples/ with runnable usage demos for all major features
All checks were successful
CI / test (push) Successful in 31s

Six examples covering the full API surface:
- basic-client: retry, timeout, logging, response size limit
- form-request: form-encoded POST for OAuth/webhooks
- load-balancing: weighted endpoints, circuit breaker, health checks
- server-basic: routing, groups, JSON helpers, health, custom 404
- server-protected: CORS, rate limiting, body limits, timeouts
- request-id-propagation: cross-service request ID forwarding

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-22 22:05:08 +03:00
parent 89cfc38f0e
commit 3aa7536328
7 changed files with 344 additions and 0 deletions

View File

@@ -0,0 +1,61 @@
// Production server with CORS, rate limiting, body size limits, and timeouts.
package main
import (
"log"
"log/slog"
"net/http"
"time"
"git.codelab.vc/pkg/httpx/server"
)
func main() {
logger := slog.Default()
r := server.NewRouter(
server.WithNotFoundHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
server.WriteError(w, http.StatusNotFound, "not found")
})),
)
r.HandleFunc("GET /api/data", func(w http.ResponseWriter, _ *http.Request) {
server.WriteJSON(w, http.StatusOK, map[string]string{"status": "ok"})
})
r.HandleFunc("POST /api/upload", func(w http.ResponseWriter, r *http.Request) {
// Body is already limited by MaxBodySize middleware.
server.WriteJSON(w, http.StatusAccepted, map[string]string{"status": "received"})
})
r.Mount("/", server.HealthHandler())
srv := server.New(r,
append(
server.Defaults(logger),
server.WithMiddleware(
// CORS for browser-facing APIs.
server.CORS(
server.AllowOrigins("https://app.example.com", "https://admin.example.com"),
server.AllowMethods("GET", "POST", "PUT", "PATCH", "DELETE"),
server.AllowHeaders("Authorization", "Content-Type"),
server.ExposeHeaders("X-Request-Id"),
server.AllowCredentials(true),
server.MaxAge(3600),
),
// Rate limit: 100 req/s per IP, burst of 200.
server.RateLimit(
server.WithRate(100),
server.WithBurst(200),
),
// Limit request body to 1 MB.
server.MaxBodySize(1<<20),
// Per-request timeout of 30 seconds.
server.Timeout(30*time.Second),
),
server.WithAddr(":8080"),
)...,
)
log.Fatal(srv.ListenAndServe())
}