Implements the top-level httpx.Client that composes the full chain: Logging → User Middlewares → Retry → Circuit Breaker → Balancer → Transport - Response wrapper with JSON/XML/Bytes decoding and body caching - NewJSONRequest helper with Content-Type and GetBody support - Functional options: WithBaseURL, WithTimeout, WithRetry, WithEndpoints, etc. - Integration tests covering retry, balancing, error mapping, and JSON round-trips
35 lines
973 B
Go
35 lines
973 B
Go
package httpx
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
)
|
|
|
|
// NewRequest creates an http.Request with context. It is a convenience
|
|
// wrapper around http.NewRequestWithContext.
|
|
func NewRequest(ctx context.Context, method, url string, body io.Reader) (*http.Request, error) {
|
|
return http.NewRequestWithContext(ctx, method, url, body)
|
|
}
|
|
|
|
// NewJSONRequest creates an http.Request with a JSON-encoded body and
|
|
// sets Content-Type to application/json.
|
|
func NewJSONRequest(ctx context.Context, method, url string, body any) (*http.Request, error) {
|
|
b, err := json.Marshal(body)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("httpx: encoding JSON body: %w", err)
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(b))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.GetBody = func() (io.ReadCloser, error) {
|
|
return io.NopCloser(bytes.NewReader(b)), nil
|
|
}
|
|
return req, nil
|
|
}
|