298 lines
8.2 KiB
Go
298 lines
8.2 KiB
Go
package httpcli
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/txix-open/isp-kit/codec"
|
|
)
|
|
|
|
// RoundTripper defines the interface for executing HTTP requests.
|
|
// Implementations can wrap requests with middleware functionality.
|
|
type RoundTripper interface {
|
|
RoundTrip(ctx context.Context, request *Request) (*Response, error)
|
|
}
|
|
|
|
// RoundTripperFunc is a function type that implements the RoundTripper interface.
|
|
type RoundTripperFunc func(ctx context.Context, request *Request) (*Response, error)
|
|
|
|
// RoundTrip executes an HTTP request using the function.
|
|
func (f RoundTripperFunc) RoundTrip(ctx context.Context, request *Request) (*Response, error) {
|
|
return f(ctx, request)
|
|
}
|
|
|
|
// Middleware is a function that wraps a RoundTripper with additional functionality.
|
|
// Middlewares are executed in the order they are added.
|
|
type Middleware func(next RoundTripper) RoundTripper
|
|
|
|
type Codec interface {
|
|
Type() string
|
|
EncodeBytes(b []byte) ([]byte, error)
|
|
Decode(r io.ReadCloser) (io.ReadCloser, error)
|
|
}
|
|
|
|
// Client is a high-level HTTP client with support for middleware, retries,
|
|
// and flexible request/response handling.
|
|
type Client struct {
|
|
cli *http.Client
|
|
globalConfig *GlobalRequestConfig
|
|
mws []Middleware
|
|
|
|
roundTripper RoundTripper
|
|
|
|
codec Codec
|
|
}
|
|
|
|
// StdClient is the default http.Client used by New() with optimized connection pooling
|
|
// and HTTP/2 support.
|
|
//
|
|
// nolint:mnd,gochecknoglobals
|
|
var (
|
|
StdClient = &http.Client{
|
|
Transport: &http.Transport{
|
|
Proxy: http.ProxyFromEnvironment,
|
|
DialContext: defaultTransportDialContext(&net.Dialer{
|
|
Timeout: 3 * time.Second,
|
|
KeepAlive: 30 * time.Second,
|
|
}),
|
|
ForceAttemptHTTP2: true,
|
|
MaxIdleConns: 512,
|
|
MaxIdleConnsPerHost: 32,
|
|
IdleConnTimeout: 90 * time.Second,
|
|
TLSHandshakeTimeout: 5 * time.Second,
|
|
ExpectContinueTimeout: 1 * time.Second,
|
|
ReadBufferSize: 8 * 1024,
|
|
WriteBufferSize: 8 * 1024,
|
|
},
|
|
}
|
|
)
|
|
|
|
// New creates a new Client with default configuration.
|
|
// It uses StdClient as the underlying http.Client.
|
|
//
|
|
// Options are applied in the order they are passed.
|
|
func New(opts ...Option) *Client {
|
|
return NewWithClient(StdClient, opts...)
|
|
}
|
|
|
|
// NewWithClient creates a new Client with a custom http.Client.
|
|
// This allows customization of the underlying transport and connection pooling.
|
|
//
|
|
// Options are applied in the order they are passed.
|
|
func NewWithClient(cli *http.Client, opts ...Option) *Client {
|
|
c := &Client{
|
|
cli: cli,
|
|
globalConfig: NewGlobalRequestConfig(),
|
|
codec: codec.Default,
|
|
}
|
|
for _, opt := range opts {
|
|
opt(c)
|
|
}
|
|
|
|
c.roundTripper = joinMiddlewares(RoundTripperFunc(c.executeWithRetries), c.mws...)
|
|
return c
|
|
}
|
|
|
|
// GlobalRequestConfig returns the global request configuration for this client.
|
|
// Settings here apply to all requests made by this client.
|
|
func (c *Client) GlobalRequestConfig() *GlobalRequestConfig {
|
|
return c.globalConfig
|
|
}
|
|
|
|
// Post creates a new POST request builder for the given URL.
|
|
func (c *Client) Post(url string) *RequestBuilder {
|
|
return NewRequestBuilder(http.MethodPost, url, c.globalConfig, c.Execute)
|
|
}
|
|
|
|
// Get creates a new GET request builder for the given URL.
|
|
func (c *Client) Get(url string) *RequestBuilder {
|
|
return NewRequestBuilder(http.MethodGet, url, c.globalConfig, c.Execute)
|
|
}
|
|
|
|
// Put creates a new PUT request builder for the given URL.
|
|
func (c *Client) Put(url string) *RequestBuilder {
|
|
return NewRequestBuilder(http.MethodPut, url, c.globalConfig, c.Execute)
|
|
}
|
|
|
|
// Delete creates a new DELETE request builder for the given URL.
|
|
func (c *Client) Delete(url string) *RequestBuilder {
|
|
return NewRequestBuilder(http.MethodDelete, url, c.globalConfig, c.Execute)
|
|
}
|
|
|
|
// Patch creates a new PATCH request builder for the given URL.
|
|
func (c *Client) Patch(url string) *RequestBuilder {
|
|
return NewRequestBuilder(http.MethodPatch, url, c.globalConfig, c.Execute)
|
|
}
|
|
|
|
// Execute sends an HTTP request using the provided builder and returns the response.
|
|
// It handles request construction, middleware execution, and response processing.
|
|
//
|
|
// If a responseBody is set on the builder and the response is successful,
|
|
// the response body will be automatically unmarshalled into the target.
|
|
//
|
|
// nolint:cyclop,funlen
|
|
func (c *Client) Execute(ctx context.Context, builder *RequestBuilder) (*Response, error) {
|
|
request, err := builder.newHttpRequest(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
for name, value := range builder.headers {
|
|
request.Header.Set(name, value)
|
|
}
|
|
for _, cookie := range builder.cookies {
|
|
request.AddCookie(cookie)
|
|
}
|
|
if builder.basicAuth != nil {
|
|
request.SetBasicAuth(builder.basicAuth.Username, builder.basicAuth.Password)
|
|
}
|
|
if builder.queryParams != nil {
|
|
values := url.Values{}
|
|
for key, value := range builder.queryParams {
|
|
values.Set(key, fmt.Sprintf("%v", value))
|
|
}
|
|
request.URL.RawQuery = values.Encode()
|
|
}
|
|
|
|
rr := &Request{
|
|
Raw: request,
|
|
timeout: builder.timeout,
|
|
retryOptions: builder.retryOptions,
|
|
decodeResponse: builder.decodeResponse,
|
|
encodeRequest: builder.encodeRequest,
|
|
encodeThreshold: builder.encodeThreshold,
|
|
}
|
|
|
|
if builder.multipartData != nil {
|
|
ct, reader := builder.multipartData.openReader()
|
|
request.Header.Set("Content-Type", ct)
|
|
request.Body = reader
|
|
}
|
|
|
|
if builder.requestBody != nil {
|
|
buff := acquireBuffer()
|
|
defer releaseBuffer(buff)
|
|
|
|
err := builder.requestBody.Write(request, buff)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
rr.body = buff.Bytes()
|
|
}
|
|
|
|
if builder.acceptEncodedResponse {
|
|
request.Header.Set("Accept-Encoding", strings.Join([]string{c.codec.Type(), "identity"}, ", "))
|
|
}
|
|
|
|
roundTripper := c.roundTripper
|
|
if len(builder.middlewares) > 0 {
|
|
roundTripper = joinMiddlewares(roundTripper, builder.middlewares...)
|
|
}
|
|
|
|
resp, err := roundTripper.RoundTrip(ctx, rr)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if resp.IsSuccess() && builder.responseBody != nil {
|
|
body, err := resp.UnsafeBody()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
err = builder.responseBody.Read(bytes.NewBuffer(body))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
return resp, nil
|
|
}
|
|
|
|
// nolint:bodyclose
|
|
func (c *Client) executeWithRetries(ctx context.Context, request *Request) (*Response, error) {
|
|
var (
|
|
response *Response
|
|
err error
|
|
)
|
|
origCtx := ctx
|
|
|
|
if request.encodeRequest && len(request.body) > request.encodeThreshold {
|
|
request.Raw.Header.Set("Content-Encoding", c.codec.Type())
|
|
request.body, err = c.codec.EncodeBytes(request.body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
_ = request.retryOptions.retrier.Do(ctx, func() error {
|
|
if response != nil {
|
|
response.Close() // prevent context and buffer leak from previous failed attempt
|
|
}
|
|
var (
|
|
ctx context.Context
|
|
cancel context.CancelFunc
|
|
)
|
|
if request.timeout > 0 {
|
|
ctx, cancel = context.WithTimeout(origCtx, request.timeout)
|
|
request.Raw = request.Raw.WithContext(ctx)
|
|
}
|
|
if request.body != nil { // it's a none multipart
|
|
request.Raw.Body = io.NopCloser(bytes.NewBuffer(request.body))
|
|
}
|
|
var resp *http.Response
|
|
resp, err = c.cli.Do(request.Raw)
|
|
buff := acquireBuffer()
|
|
response = &Response{
|
|
Raw: resp,
|
|
buff: buff,
|
|
cancel: cancel,
|
|
}
|
|
retryErr := request.retryOptions.condition(err, response)
|
|
return retryErr
|
|
})
|
|
|
|
if err != nil || !request.decodeResponse {
|
|
return response, err
|
|
}
|
|
|
|
enc := response.Raw.Header.Get("Content-Encoding")
|
|
if enc != c.codec.Type() {
|
|
return response, nil
|
|
}
|
|
|
|
response.Raw.Body, err = c.codec.Decode(response.Raw.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
response.Raw.Header.Del("Content-Encoding")
|
|
response.Raw.Header.Del("Content-Length")
|
|
return response, nil
|
|
}
|
|
|
|
// defaultTransportDialContext creates a dial context function with the given dialer.
|
|
func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) {
|
|
return dialer.DialContext
|
|
}
|
|
|
|
// joinMiddlewares chains multiple middlewares together, wrapping the root RoundTripper.
|
|
// Middlewares are applied in reverse order (last middleware is executed first).
|
|
//
|
|
// nolint:ireturn
|
|
func joinMiddlewares(root RoundTripper, mws ...Middleware) RoundTripper {
|
|
roundTripper := root
|
|
for _, mw := range slices.Backward(mws) {
|
|
roundTripper = mw(roundTripper)
|
|
}
|
|
return roundTripper
|
|
}
|