Files
Aleksey Shakhmatov 3aa7536328
All checks were successful
CI / test (push) Successful in 31s
Add examples/ with runnable usage demos for all major features
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>
2026-03-22 22:05:08 +03:00

68 lines
1.3 KiB
Go

// Basic HTTP client with retry, timeout, and structured logging.
package main
import (
"context"
"fmt"
"log"
"log/slog"
"time"
"git.codelab.vc/pkg/httpx"
"git.codelab.vc/pkg/httpx/middleware"
"git.codelab.vc/pkg/httpx/retry"
)
func main() {
client := httpx.New(
httpx.WithBaseURL("https://httpbin.org"),
httpx.WithTimeout(10*time.Second),
httpx.WithRetry(
retry.WithMaxAttempts(3),
retry.WithBackoff(retry.ExponentialBackoff(100*time.Millisecond, 2*time.Second, true)),
),
httpx.WithMiddleware(
middleware.UserAgent("httpx-example/1.0"),
),
httpx.WithMaxResponseBody(1<<20), // 1 MB limit
httpx.WithLogger(slog.Default()),
)
defer client.Close()
ctx := context.Background()
// GET request.
resp, err := client.Get(ctx, "/get")
if err != nil {
log.Fatal(err)
}
body, err := resp.String()
if err != nil {
log.Fatal(err)
}
fmt.Printf("GET /get → %d (%d bytes)\n", resp.StatusCode, len(body))
// POST with JSON body.
type payload struct {
Name string `json:"name"`
Email string `json:"email"`
}
req, err := httpx.NewJSONRequest(ctx, "POST", "/post", payload{
Name: "Alice",
Email: "alice@example.com",
})
if err != nil {
log.Fatal(err)
}
resp, err = client.Do(ctx, req)
if err != nil {
log.Fatal(err)
}
defer resp.Close()
fmt.Printf("POST /post → %d\n", resp.StatusCode)
}