Add examples/ with runnable usage demos for all major features
All checks were successful
CI / test (push) Successful in 31s
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:
54
examples/request-id-propagation/main.go
Normal file
54
examples/request-id-propagation/main.go
Normal file
@@ -0,0 +1,54 @@
|
||||
// Demonstrates request ID propagation between server and client.
|
||||
// The server assigns a request ID to incoming requests, and the client
|
||||
// middleware forwards it to downstream services via X-Request-Id header.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"git.codelab.vc/pkg/httpx"
|
||||
"git.codelab.vc/pkg/httpx/middleware"
|
||||
"git.codelab.vc/pkg/httpx/server"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger := slog.Default()
|
||||
|
||||
// Client that propagates request IDs from context.
|
||||
client := httpx.New(
|
||||
httpx.WithBaseURL("http://localhost:9090"),
|
||||
httpx.WithMiddleware(
|
||||
middleware.RequestID(), // Picks up ID from context, sets X-Request-Id.
|
||||
),
|
||||
)
|
||||
defer client.Close()
|
||||
|
||||
r := server.NewRouter()
|
||||
|
||||
r.HandleFunc("GET /proxy", func(w http.ResponseWriter, r *http.Request) {
|
||||
// The request ID is in r.Context() thanks to server.RequestID().
|
||||
id := server.RequestIDFromContext(r.Context())
|
||||
logger.Info("handling request", "request_id", id)
|
||||
|
||||
// Client automatically forwards the request ID to downstream.
|
||||
resp, err := client.Get(r.Context(), "/downstream")
|
||||
if err != nil {
|
||||
server.WriteError(w, http.StatusBadGateway, fmt.Sprintf("downstream error: %v", err))
|
||||
return
|
||||
}
|
||||
defer resp.Close()
|
||||
|
||||
body, _ := resp.String()
|
||||
server.WriteJSON(w, http.StatusOK, map[string]string{
|
||||
"request_id": id,
|
||||
"downstream_response": body,
|
||||
})
|
||||
})
|
||||
|
||||
// Server with RequestID middleware that assigns IDs to incoming requests.
|
||||
srv := server.New(r, server.Defaults(logger)...)
|
||||
log.Fatal(srv.ListenAndServe())
|
||||
}
|
||||
Reference in New Issue
Block a user