MSP-8172 Add vendor
This commit is contained in:
1 parent
5175d87e08
commit
eb066cb055
2619 files changed
+757077
-2
No files matched your search
+258
@@ -0,0 +1,258 @@
|
||||
# Package `httpcli`
|
||||
|
||||
Пакет `httpcli` предоставляет расширенный HTTP-клиент с поддержкой middleware, ретраев, различных типов запросов и
|
||||
обработки ошибок.
|
||||
Интегрируется с системами логирования, метриками и политиками повторов.
|
||||
|
||||
## Types
|
||||
|
||||
### Client
|
||||
|
||||
Основная структура для выполнения HTTP-запросов. Управляет настройками транспорта, middleware и глобальными параметрами.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `New(opts ...Option) *Client`
|
||||
|
||||
Конструктор клиента с настройками по умолчанию. Принимает опции:
|
||||
|
||||
- `WithMiddlewares(mws ...Middleware) Option` – добавляет цепочку middleware к запросам клиента.
|
||||
- `WithCodec(codec Codec) Option` – переопределяет codec для кодирования/декодирования, по умолчанию стоит `zstd`
|
||||
|
||||
#### `NewWithClient(cli *http.Client, opts ...Option) *Client`
|
||||
|
||||
Конструктор клиента на основе базового клиента из стандартной библиотеки `net/http`.
|
||||
|
||||
#### `(c *Client) GlobalRequestConfig() *GlobalRequestConfig`
|
||||
|
||||
Получить глобальную конфигурацию запросов (таймауты, базовый URL, заголовки и т.д.).
|
||||
|
||||
#### `(c *Client) Post(url string) *RequestBuilder`
|
||||
|
||||
Создать билдер для POST-запроса. Аналогичные методы: `Get()`, `Put()`, `Delete()`, `Patch()`.
|
||||
|
||||
#### `(c *Client) Execute(ctx context.Context, builder *RequestBuilder) (*Response, error)`
|
||||
|
||||
Выполнить HTTP-запрос из переданного билдера.
|
||||
|
||||
### RequestBuilder
|
||||
|
||||
Структура для построения HTTP-запросов с цепочкой методов.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `(b *RequestBuilder) Header(name string, value string) *RequestBuilder`
|
||||
|
||||
Добавить заголовок к запросу.
|
||||
|
||||
#### `(b *RequestBuilder) BaseUrl(baseUrl string) *RequestBuilder`
|
||||
|
||||
Установить базовый url в запросе на переданный.
|
||||
|
||||
#### `(b *RequestBuilder) Url(url string) *RequestBuilder`
|
||||
|
||||
Установить url запроса на переданный.
|
||||
|
||||
#### `(b *RequestBuilder) Method(method string) *RequestBuilder`
|
||||
|
||||
Изменить HTTP-метод запроса на указанный.
|
||||
|
||||
#### `(b *RequestBuilder) Cookie(cookie *http.Cookie) *RequestBuilder`
|
||||
|
||||
Добавить cookie к запросу.
|
||||
|
||||
#### `(b *RequestBuilder) RequestBody(body []byte) *RequestBuilder`
|
||||
|
||||
Добавить тело запроса.
|
||||
|
||||
#### `(b *RequestBuilder) JsonRequestBody(value any) *RequestBuilder`
|
||||
|
||||
Добавить тело запроса в формате JSON. Использует пакет [`json`](../../json), поэтому может маршалить без тэгов в
|
||||
camelCase.
|
||||
|
||||
#### `(b *RequestBuilder) JsonResponseBody(responsePtr any) *RequestBuilder`
|
||||
|
||||
Записать JSON-ответ на запрос по переданному указателю. Операция выполнится только при статус кодах от 200 до 299.
|
||||
|
||||
#### `(b *RequestBuilder) FormDataRequestBody(data map[string][]string) *RequestBuilder`
|
||||
|
||||
Добавить тело запроса в формате формы.
|
||||
|
||||
#### `(b *RequestBuilder) BasicAuth(ba BasicAuth) *RequestBuilder`
|
||||
|
||||
Добавить базую аутентификацию в запрос.
|
||||
|
||||
#### `(b *RequestBuilder) QueryParams(queryParams map[string]any) *RequestBuilder`
|
||||
|
||||
Добавить query-параметры в запрос.
|
||||
|
||||
#### `(b *RequestBuilder) Retry(cond RetryCondition, retryer Retryer) *RequestBuilder`
|
||||
|
||||
Задать политику ретраев по заданному условию. Пример условия: `httpcli.IfErrorOr5XXStatus()`
|
||||
|
||||
#### `(b *RequestBuilder) MultipartRequestBody(data *MultipartData) *RequestBuilder`
|
||||
|
||||
Устанавить multipart/form-data тело запроса (для передачи файлов). Не поддерживает `Request.Body` в middleware и
|
||||
игнорирует ретраи.
|
||||
|
||||
#### `(b *RequestBuilder) StatusCodeToError() *RequestBuilder`
|
||||
|
||||
Возвращает `ErrorResponse` как ошибку при `Response.IsSuccess = true`.
|
||||
|
||||
#### `(b *RequestBuilder) Timeout(timeout time.Duration) *RequestBuilder`
|
||||
|
||||
Установить тайм-аут для каждой попытки запроса, тайм-аут по умолчанию 15 секунд.
|
||||
|
||||
#### `(b *RequestBuilder) Middlewares(middlewares ...Middleware) *RequestBuilder`
|
||||
|
||||
Добавить middleware в цепочку запроса.
|
||||
|
||||
#### `(b *RequestBuilder) EncodeRequest(encode bool) *RequestBuilder`
|
||||
|
||||
Установить флаг кодирования запроса.
|
||||
Если включен и запрос по размеру больше заданного threshold, то в заголовки запроса будет добавлен `Content-Encoding` со значением типа codec и тело запроса будет закодировано.
|
||||
|
||||
#### `(b *RequestBuilder) EncodeThreshold(threshold int) *RequestBuilder`
|
||||
|
||||
Установить threshold в байтах, выше которого будет применяться кодирование запроса (при включённом флаге encodeRequest).
|
||||
|
||||
#### `(b *RequestBuilder) AcceptEncodedResponse(accept bool) *RequestBuilder`
|
||||
|
||||
Установить флаг приёма закодированных ответов.
|
||||
Если включен, то в заголовки запроса будет добавлен `Accept-Encoding` со значением типа codec + identity (пример `zstd, identity`).
|
||||
|
||||
#### `(b *RequestBuilder) DecodeResponse(decode bool) *RequestBuilder`
|
||||
|
||||
Установить флаг декодирования ответа.
|
||||
Если включен, то ответ сервера с заголовком `Content-Encoding` типом codec в клиенте будет декодирован.
|
||||
|
||||
#### `(b *RequestBuilder) Do(ctx context.Context) (*Response, error)`
|
||||
|
||||
Выполнить запрос собранный билдером.
|
||||
|
||||
#### `(b *RequestBuilder) DoWithoutResponse(ctx context.Context) error`
|
||||
|
||||
То же самое, что и `Do`, но записывает ответ по переданному раннее в билдере указателю.
|
||||
|
||||
#### `(b *RequestBuilder) DoWithoutResponse(ctx context.Context) error`
|
||||
|
||||
То же самое, что и `Do`, но не возвращает объект `Response`. Записывает тело ответа по переданному в метод
|
||||
`JsonResponseBody` указателю.
|
||||
|
||||
#### `(b *RequestBuilder) DoAndReadBody(ctx context.Context) ([]byte, int, error)`
|
||||
|
||||
То же самое, что и `Do`, но считывает из ответа только тело и статус код, а затем возвращает их.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
)
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func main() {
|
||||
cli := httpcli.New()
|
||||
u := new(user)
|
||||
|
||||
resp, err := cli.Get("https://api.example.com/users/1").
|
||||
JsonResponseBody(u).
|
||||
Do(context.Background())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer resp.Close()
|
||||
|
||||
if !resp.IsSuccess() {
|
||||
log.Fatalf("invalid status code: %d", resp.StatusCode())
|
||||
}
|
||||
log.Println(u.Name) /* result decoded from JSON */
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Without response
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
)
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func main() {
|
||||
cli := httpcli.New()
|
||||
u := new(user)
|
||||
|
||||
err := cli.Get("https://api.example.com/users/1").
|
||||
JsonResponseBody(u).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(context.Background())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Println(u.Name) /* result decoded from JSON */
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Exponential retries
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/retry"
|
||||
)
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
const (
|
||||
maxRetryElapsedTime = 5 * time.Second
|
||||
)
|
||||
|
||||
func main() {
|
||||
cli := httpcli.New()
|
||||
u := user{
|
||||
Id: "x.x",
|
||||
Name: "Mark",
|
||||
}
|
||||
|
||||
err := cli.Post("https://api.example.com/users").
|
||||
JsonRequestBody(u).
|
||||
Retry(httpcli.IfErrorOr5XXStatus(), retry.NewExponentialBackoff(maxRetryElapsedTime)).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(context.Background())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package httpcli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// nolint:gochecknoglobals,mnd
|
||||
var (
|
||||
bpool = sync.Pool{New: func() any {
|
||||
return bytes.NewBuffer(make([]byte, 1024))
|
||||
}}
|
||||
)
|
||||
|
||||
func acquireBuffer() *bytes.Buffer {
|
||||
buf := bpool.Get().(*bytes.Buffer) // nolint:forcetypeassert
|
||||
buf.Reset()
|
||||
return buf
|
||||
}
|
||||
|
||||
func releaseBuffer(buf *bytes.Buffer) {
|
||||
bpool.Put(buf)
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package httpcli
|
||||
|
||||
// BasicAuth holds HTTP basic authentication credentials.
|
||||
type BasicAuth struct {
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package httpcli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
// RequestBodyWriter defines the interface for writing request bodies.
|
||||
type RequestBodyWriter interface {
|
||||
Write(req *http.Request, w io.Writer) error
|
||||
}
|
||||
|
||||
// jsonRequest handles JSON-encoded request bodies.
|
||||
type jsonRequest struct {
|
||||
value any
|
||||
}
|
||||
|
||||
// Write sets the Content-Type header to application/json and encodes the value as JSON.
|
||||
func (j jsonRequest) Write(req *http.Request, w io.Writer) error {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
return json.EncodeInto(w, j.value)
|
||||
}
|
||||
|
||||
// plainRequest handles raw byte request bodies.
|
||||
type plainRequest struct {
|
||||
value []byte
|
||||
}
|
||||
|
||||
// Write writes the raw bytes to the request body.
|
||||
func (p plainRequest) Write(_ *http.Request, w io.Writer) error {
|
||||
_, err := w.Write(p.value)
|
||||
return err
|
||||
}
|
||||
|
||||
// formRequest handles form-encoded request bodies.
|
||||
type formRequest struct {
|
||||
data map[string][]string
|
||||
}
|
||||
|
||||
// Write sets the Content-Type header to application/x-www-form-urlencoded
|
||||
// and encodes the data as form parameters.
|
||||
func (f formRequest) Write(req *http.Request, w io.Writer) error {
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
data := url.Values(f.data).Encode()
|
||||
_, err := w.Write([]byte(data))
|
||||
return err
|
||||
}
|
||||
|
||||
// ResponseBodyReader defines the interface for reading response bodies.
|
||||
type ResponseBodyReader interface {
|
||||
Read(r io.Reader) error
|
||||
}
|
||||
|
||||
// jsonResponse handles JSON-encoded response bodies.
|
||||
type jsonResponse struct {
|
||||
ptr any
|
||||
}
|
||||
|
||||
// Read unmarshals the response body into the target pointer.
|
||||
// Uses optimized unmarshaling when the source is a bytes.Buffer.
|
||||
func (j jsonResponse) Read(r io.Reader) error {
|
||||
buff, isBuff := r.(*bytes.Buffer)
|
||||
if isBuff {
|
||||
return json.Unmarshal(buff.Bytes(), j.ptr)
|
||||
}
|
||||
return json.NewDecoder(r).Decode(j.ptr)
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
package httpcli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"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 i := len(mws) - 1; i >= 0; i-- {
|
||||
roundTripper = mws[i](roundTripper)
|
||||
}
|
||||
return roundTripper
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
// Package httpcli provides a high-level HTTP client with support for middleware,
|
||||
// retries, and flexible request/response handling.
|
||||
//
|
||||
// The package offers a builder pattern API for constructing HTTP requests with
|
||||
// various options including headers, cookies, authentication, and request bodies.
|
||||
package httpcli
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package httpcli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// ErrorResponse represents an HTTP error response with status code and body.
|
||||
//
|
||||
// nolint:errname
|
||||
type ErrorResponse struct {
|
||||
Url *url.URL
|
||||
StatusCode int
|
||||
Body []byte
|
||||
}
|
||||
|
||||
// Error returns a formatted error message containing the URL, status code, and body.
|
||||
func (e ErrorResponse) Error() string {
|
||||
return fmt.Sprintf("http call error: url=%s status_code=%d, body=%s", e.Url.String(), e.StatusCode, e.Body)
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package httpcli
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/codec"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultTimeout = 15 * time.Second
|
||||
defaultEncodeThreshold = codec.DefaultEncodeThreshold
|
||||
)
|
||||
|
||||
// GlobalRequestConfig holds default settings that apply to all requests
|
||||
// created by a Client.
|
||||
type GlobalRequestConfig struct {
|
||||
// Timeout specifies the request timeout.
|
||||
Timeout time.Duration
|
||||
|
||||
// BaseUrl specifies the base URL for requests.
|
||||
BaseUrl string
|
||||
|
||||
// BasicAuth specifies HTTP Basic Authentication credentials.
|
||||
BasicAuth *BasicAuth
|
||||
|
||||
// Cookies contains cookies sent with every request.
|
||||
Cookies []*http.Cookie
|
||||
|
||||
// Headers contains headers sent with every request.
|
||||
Headers map[string]string
|
||||
|
||||
// AcceptEncodedResponse enables automatic acceptance of encoded responses.
|
||||
AcceptEncodedResponse bool
|
||||
|
||||
// EncodeRequest enables request body encoding.
|
||||
EncodeRequest bool
|
||||
|
||||
// DecodeResponse enables response body decoding.
|
||||
DecodeResponse bool
|
||||
|
||||
// EncodeThreshold specifies the request encoding threshold in bytes.
|
||||
EncodeThreshold int
|
||||
}
|
||||
|
||||
// NewGlobalRequestConfig creates a new GlobalRequestConfig with default values.
|
||||
//
|
||||
// Default timeout is 15 seconds.
|
||||
// Default EncodeThreshold - 128Kb
|
||||
// By default client accept encoded response.
|
||||
func NewGlobalRequestConfig() *GlobalRequestConfig {
|
||||
return &GlobalRequestConfig{
|
||||
Timeout: defaultTimeout,
|
||||
AcceptEncodedResponse: true,
|
||||
DecodeResponse: true,
|
||||
EncodeRequest: false,
|
||||
EncodeThreshold: defaultEncodeThreshold,
|
||||
}
|
||||
}
|
||||
|
||||
// configure applies the global settings to a RequestBuilder.
|
||||
func (c *GlobalRequestConfig) configure(req *RequestBuilder) {
|
||||
req.timeout = c.Timeout
|
||||
req.baseUrl = c.BaseUrl
|
||||
req.basicAuth = c.BasicAuth
|
||||
req.cookies = append(req.cookies, c.Cookies...)
|
||||
for name, value := range c.Headers {
|
||||
req.Header(name, value)
|
||||
}
|
||||
req.acceptEncodedResponse = c.AcceptEncodedResponse
|
||||
req.decodeResponse = c.DecodeResponse
|
||||
req.encodeRequest = c.EncodeRequest
|
||||
req.encodeThreshold = c.EncodeThreshold
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package httpcli
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// SetContentLength is a middleware that sets the Content-Length header for requests
|
||||
// with a known body size.
|
||||
//
|
||||
// Skips setting Content-Length for multipart requests where the size is unknown.
|
||||
func SetContentLength() Middleware {
|
||||
transferEncoding := []string{"identity"}
|
||||
return func(next RoundTripper) RoundTripper {
|
||||
return RoundTripperFunc(func(ctx context.Context, request *Request) (*Response, error) {
|
||||
if request.body == nil { // multipart
|
||||
return next.RoundTrip(ctx, request)
|
||||
}
|
||||
|
||||
request.Raw.ContentLength = int64(len(request.body))
|
||||
request.Raw.TransferEncoding = transferEncoding
|
||||
return next.RoundTrip(ctx, request)
|
||||
})
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package httpcli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/textproto"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MultipartData holds multipart/form-data request content including files and values.
|
||||
type MultipartData struct {
|
||||
Files map[string]MultipartFieldFile
|
||||
Values map[string]string
|
||||
}
|
||||
|
||||
// MultipartFieldFile represents a single file in a multipart form.
|
||||
type MultipartFieldFile struct {
|
||||
Headers map[string]string
|
||||
Filename string
|
||||
Reader io.ReadCloser
|
||||
}
|
||||
|
||||
// openReader creates a pipe reader that streams the multipart form data.
|
||||
// Returns the content type and the reader.
|
||||
func (m *MultipartData) openReader() (string, io.ReadCloser) {
|
||||
pr, pw := io.Pipe()
|
||||
writer := multipart.NewWriter(pw)
|
||||
go func() {
|
||||
defer func() {
|
||||
_ = writer.Close()
|
||||
_ = pw.Close()
|
||||
for _, file := range m.Files {
|
||||
_ = file.Reader.Close()
|
||||
}
|
||||
}()
|
||||
for key, value := range m.Values {
|
||||
err := writer.WriteField(key, value)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
for name, file := range m.Files {
|
||||
wr, err := CreateFormFile(writer, file.Headers, name, file.Filename)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, err = io.Copy(wr, file.Reader)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return writer.FormDataContentType(), pr
|
||||
}
|
||||
|
||||
// CreateFormFile creates a form file part in the multipart writer with custom headers.
|
||||
//
|
||||
// Sets the Content-Disposition header with the field name and filename.
|
||||
func CreateFormFile(
|
||||
w *multipart.Writer,
|
||||
header map[string]string,
|
||||
fieldname string,
|
||||
filename string,
|
||||
) (io.Writer, error) {
|
||||
h := make(textproto.MIMEHeader)
|
||||
for key, value := range header {
|
||||
h.Set(key, value)
|
||||
}
|
||||
h.Set("Content-Disposition",
|
||||
fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
|
||||
escapeQuotes(fieldname), escapeQuotes(filename)))
|
||||
return w.CreatePart(h)
|
||||
}
|
||||
|
||||
// nolint:gochecknoglobals
|
||||
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
|
||||
|
||||
// escapeQuotes escapes quotes and backslashes in strings for multipart form data.
|
||||
func escapeQuotes(s string) string {
|
||||
return quoteEscaper.Replace(s)
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package httpcli
|
||||
|
||||
// Option is a function that configures a Client.
|
||||
type Option func(c *Client)
|
||||
|
||||
// WithMiddlewares adds one or more middlewares to the client.
|
||||
// Middlewares are executed in the order they are provided.
|
||||
func WithMiddlewares(mws ...Middleware) Option {
|
||||
return func(c *Client) {
|
||||
c.mws = append(c.mws, mws...)
|
||||
}
|
||||
}
|
||||
|
||||
// WithCodec sets codec.
|
||||
func WithCodec(codec Codec) Option {
|
||||
return func(c *Client) {
|
||||
c.codec = codec
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package httpcli
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Request wraps an http.Request with additional metadata for middleware processing.
|
||||
type Request struct {
|
||||
Raw *http.Request
|
||||
|
||||
retryOptions *retryOptions
|
||||
body []byte
|
||||
timeout time.Duration
|
||||
|
||||
decodeResponse bool
|
||||
encodeRequest bool
|
||||
encodeThreshold int
|
||||
}
|
||||
|
||||
// Body returns the request body as bytes.
|
||||
//
|
||||
// Returns an empty slice if MultipartRequestBody was used, as multipart data
|
||||
// is streamed directly and not buffered.
|
||||
func (r *Request) Body() []byte {
|
||||
return r.body
|
||||
}
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
package httpcli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RequestBuilder provides a fluent API for constructing HTTP requests.
|
||||
// It supports method chaining for setting various request options.
|
||||
type RequestBuilder struct {
|
||||
method string
|
||||
url string
|
||||
baseUrl string
|
||||
headers map[string]string
|
||||
cookies []*http.Cookie
|
||||
requestBody RequestBodyWriter
|
||||
responseBody ResponseBodyReader
|
||||
multipartData *MultipartData
|
||||
basicAuth *BasicAuth
|
||||
queryParams map[string]any
|
||||
retryOptions *retryOptions
|
||||
timeout time.Duration
|
||||
statusCodeToError bool
|
||||
middlewares []Middleware
|
||||
|
||||
encodeRequest bool
|
||||
acceptEncodedResponse bool
|
||||
decodeResponse bool
|
||||
encodeThreshold int
|
||||
|
||||
execute func(ctx context.Context, req *RequestBuilder) (*Response, error)
|
||||
}
|
||||
|
||||
// NewRequestBuilder creates a new RequestBuilder with the given HTTP method, URL,
|
||||
// global configuration, and execute function.
|
||||
func NewRequestBuilder(
|
||||
method string,
|
||||
url string,
|
||||
cfg *GlobalRequestConfig,
|
||||
execute func(ctx context.Context, req *RequestBuilder) (*Response, error),
|
||||
) *RequestBuilder {
|
||||
builder := &RequestBuilder{
|
||||
method: method,
|
||||
url: url,
|
||||
execute: execute,
|
||||
retryOptions: noRetries,
|
||||
}
|
||||
cfg.configure(builder)
|
||||
return builder
|
||||
}
|
||||
|
||||
// BaseUrl sets the base URL that will be prepended to the request URL.
|
||||
// Useful for API clients with a fixed base path.
|
||||
func (b *RequestBuilder) BaseUrl(baseUrl string) *RequestBuilder {
|
||||
b.baseUrl = baseUrl
|
||||
return b
|
||||
}
|
||||
|
||||
// Url sets the request URL, overriding any previously set URL.
|
||||
func (b *RequestBuilder) Url(url string) *RequestBuilder {
|
||||
b.url = url
|
||||
return b
|
||||
}
|
||||
|
||||
// Method sets the HTTP method for the request.
|
||||
func (b *RequestBuilder) Method(method string) *RequestBuilder {
|
||||
b.method = method
|
||||
return b
|
||||
}
|
||||
|
||||
// Header sets a request header with the given name and value.
|
||||
func (b *RequestBuilder) Header(name string, value string) *RequestBuilder {
|
||||
if b.headers == nil {
|
||||
b.headers = map[string]string{}
|
||||
}
|
||||
b.headers[name] = value
|
||||
return b
|
||||
}
|
||||
|
||||
// Cookie adds a cookie to the request.
|
||||
func (b *RequestBuilder) Cookie(cookie *http.Cookie) *RequestBuilder {
|
||||
b.cookies = append(b.cookies, cookie)
|
||||
return b
|
||||
}
|
||||
|
||||
// RequestBody sets the request body from a byte slice.
|
||||
func (b *RequestBuilder) RequestBody(body []byte) *RequestBuilder {
|
||||
b.multipartData = nil
|
||||
b.requestBody = plainRequest{value: body}
|
||||
return b
|
||||
}
|
||||
|
||||
// JsonRequestBody sets the request body as JSON from the given value.
|
||||
// Sets Content-Type to application/json.
|
||||
func (b *RequestBuilder) JsonRequestBody(value any) *RequestBuilder {
|
||||
b.multipartData = nil
|
||||
b.requestBody = jsonRequest{value: value}
|
||||
return b
|
||||
}
|
||||
|
||||
// JsonResponseBody configures the builder to unmarshal the JSON response body
|
||||
// into the provided pointer if the status code is in the 2xx range.
|
||||
func (b *RequestBuilder) JsonResponseBody(responsePtr any) *RequestBuilder {
|
||||
b.responseBody = jsonResponse{ptr: responsePtr}
|
||||
return b
|
||||
}
|
||||
|
||||
// FormDataRequestBody sets the request body as form-encoded data.
|
||||
// Sets Content-Type to application/x-www-form-urlencoded.
|
||||
func (b *RequestBuilder) FormDataRequestBody(data map[string][]string) *RequestBuilder {
|
||||
b.multipartData = nil
|
||||
b.requestBody = formRequest{data: data}
|
||||
return b
|
||||
}
|
||||
|
||||
// BasicAuth sets HTTP basic authentication credentials for the request.
|
||||
func (b *RequestBuilder) BasicAuth(ba BasicAuth) *RequestBuilder {
|
||||
b.basicAuth = &ba
|
||||
return b
|
||||
}
|
||||
|
||||
// QueryParams sets query parameters for the request URL.
|
||||
// Values are converted to strings using fmt.Sprintf.
|
||||
func (b *RequestBuilder) QueryParams(queryParams map[string]any) *RequestBuilder {
|
||||
b.queryParams = queryParams
|
||||
return b
|
||||
}
|
||||
|
||||
// Retry configures retry behavior for the request.
|
||||
// The condition determines when to retry, and the retryer controls the retry logic.
|
||||
func (b *RequestBuilder) Retry(cond RetryCondition, retryer Retryer) *RequestBuilder {
|
||||
b.retryOptions = &retryOptions{
|
||||
condition: cond,
|
||||
retrier: retryer,
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// MultipartRequestBody sets up multipart/form-data request with files and values.
|
||||
//
|
||||
// This is useful for uploading large files as data is streamed and not buffered in memory.
|
||||
//
|
||||
// Note: This disables retry support and request body access in middlewares.
|
||||
func (b *RequestBuilder) MultipartRequestBody(data *MultipartData) *RequestBuilder {
|
||||
b.requestBody = nil
|
||||
b.retryOptions = noRetries
|
||||
b.multipartData = data
|
||||
return b
|
||||
}
|
||||
|
||||
// StatusCodeToError enables automatic error conversion for non-success status codes.
|
||||
//
|
||||
// When enabled and the response status is not in the 2xx range, Do() returns
|
||||
// an ErrorResponse containing the status code and body.
|
||||
func (b *RequestBuilder) StatusCodeToError() *RequestBuilder {
|
||||
b.statusCodeToError = true
|
||||
return b
|
||||
}
|
||||
|
||||
// Timeout sets the timeout duration for the request attempt.
|
||||
//
|
||||
// Defaults to 15 seconds if not specified.
|
||||
func (b *RequestBuilder) Timeout(timeout time.Duration) *RequestBuilder {
|
||||
b.timeout = timeout
|
||||
return b
|
||||
}
|
||||
|
||||
// Middlewares adds one or more middlewares to be executed for this specific request.
|
||||
// These are executed after the client's global middlewares.
|
||||
func (b *RequestBuilder) Middlewares(middlewares ...Middleware) *RequestBuilder {
|
||||
b.middlewares = append(b.middlewares, middlewares...)
|
||||
return b
|
||||
}
|
||||
|
||||
// EncodeRequest sets encoding for request body.
|
||||
// It affects Content-Encoding and request body serialization.
|
||||
func (b *RequestBuilder) EncodeRequest(encode bool) *RequestBuilder {
|
||||
b.encodeRequest = encode
|
||||
return b
|
||||
}
|
||||
|
||||
// EncodeThreshold sets the request encoding threshold in bytes.
|
||||
func (b *RequestBuilder) EncodeThreshold(thresholdBytes int) *RequestBuilder {
|
||||
b.encodeThreshold = thresholdBytes
|
||||
return b
|
||||
}
|
||||
|
||||
// AcceptEncodedResponse sets transparent handling of encoded HTTP responses.
|
||||
//
|
||||
// When enabled, the client adds "Accept-Encoding" (e.g. zstd) to request headers,
|
||||
// allowing the server to return encoded payloads.
|
||||
func (b *RequestBuilder) AcceptEncodedResponse(accept bool) *RequestBuilder {
|
||||
b.acceptEncodedResponse = accept
|
||||
return b
|
||||
}
|
||||
|
||||
// DecodeResponse sets response decoding.
|
||||
//
|
||||
// When disabled response body will be returned as-is.
|
||||
func (b *RequestBuilder) DecodeResponse(decode bool) *RequestBuilder {
|
||||
b.decodeResponse = decode
|
||||
return b
|
||||
}
|
||||
|
||||
// Do executes the request and returns the response.
|
||||
//
|
||||
// Returns the response and any error that occurred during execution.
|
||||
// If StatusCodeToError was called and the response is not successful,
|
||||
// returns ErrorResponse as the error.
|
||||
func (b *RequestBuilder) Do(ctx context.Context) (*Response, error) {
|
||||
resp, err := b.execute(ctx, b)
|
||||
b.execute = nil
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !resp.IsSuccess() && b.statusCodeToError {
|
||||
body, err := resp.BodyCopy()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, ErrorResponse{
|
||||
Url: resp.Raw.Request.URL,
|
||||
StatusCode: resp.StatusCode(),
|
||||
Body: body,
|
||||
}
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// DoWithoutResponse executes the request and discards the response.
|
||||
//
|
||||
// Returns any error that occurred during execution.
|
||||
// Automatically closes the response to release resources.
|
||||
func (b *RequestBuilder) DoWithoutResponse(ctx context.Context) error {
|
||||
resp, err := b.Do(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
// DoAndReadBody executes the request and returns the response body.
|
||||
//
|
||||
// Returns the response body, status code, and any error.
|
||||
// Automatically closes the response to release resources.
|
||||
func (b *RequestBuilder) DoAndReadBody(ctx context.Context) ([]byte, int, error) {
|
||||
resp, err := b.Do(ctx)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer resp.Close()
|
||||
|
||||
body, err := resp.BodyCopy()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return body, resp.StatusCode(), nil
|
||||
}
|
||||
|
||||
// newHttpRequest creates an http.Request from the builder configuration.
|
||||
func (b *RequestBuilder) newHttpRequest(ctx context.Context) (*http.Request, error) {
|
||||
targetUrl := b.baseUrl
|
||||
if targetUrl == "" {
|
||||
targetUrl = b.url
|
||||
}
|
||||
|
||||
request, err := http.NewRequestWithContext(ctx, b.method, targetUrl, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if b.baseUrl != "" {
|
||||
if !strings.HasSuffix(request.URL.Path, "/") {
|
||||
request.URL.Path += "/"
|
||||
}
|
||||
request.URL = request.URL.JoinPath(b.url)
|
||||
}
|
||||
|
||||
return request, nil
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package httpcli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Response wraps an http.Response with buffering and lifecycle management.
|
||||
type Response struct {
|
||||
Raw *http.Response
|
||||
|
||||
cancel context.CancelFunc
|
||||
body []byte
|
||||
err error
|
||||
buff *bytes.Buffer
|
||||
}
|
||||
|
||||
// ReadingResponseMetricHook is a context key for hooks that are called when
|
||||
// the response body is fully read. Used for metrics collection.
|
||||
type ReadingResponseMetricHook struct{}
|
||||
|
||||
// nolint:gochecknoglobals
|
||||
var (
|
||||
ReadingResponseMetricHookKey = ReadingResponseMetricHook{}
|
||||
)
|
||||
|
||||
// UnsafeBody reads and returns the full response body as bytes.
|
||||
//
|
||||
// After calling Close(), the returned data is no longer valid.
|
||||
// Use BodyCopy() if you need the data after calling Close().
|
||||
//
|
||||
// Do not call Close() or modify the returned slice if you want to use
|
||||
// the data outside the current scope.
|
||||
func (r *Response) UnsafeBody() ([]byte, error) {
|
||||
if r.err != nil {
|
||||
return nil, r.err
|
||||
}
|
||||
if r.body != nil {
|
||||
return r.body, nil
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if r.cancel != nil {
|
||||
r.cancel() // associated context is no longer needed
|
||||
r.cancel = nil
|
||||
}
|
||||
}()
|
||||
_, err := io.Copy(r.buff, r.Raw.Body)
|
||||
if err != nil {
|
||||
r.err = err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if hook, ok := r.Raw.Request.Context().Value(ReadingResponseMetricHookKey).(func()); ok {
|
||||
hook()
|
||||
}
|
||||
|
||||
r.body = r.buff.Bytes()
|
||||
return r.body, nil
|
||||
}
|
||||
|
||||
// Close releases all resources associated with the Response, including buffers,
|
||||
// TCP connections, and context.
|
||||
//
|
||||
// After calling Close(), any bytes slice returned by UnsafeBody() or BodyCopy()
|
||||
// should not be accessed.
|
||||
func (r *Response) Close() {
|
||||
if r.cancel != nil {
|
||||
r.cancel()
|
||||
r.cancel = nil
|
||||
}
|
||||
if r.Raw != nil {
|
||||
_ = r.Raw.Body.Close()
|
||||
}
|
||||
r.body = nil
|
||||
releaseBuffer(r.buff)
|
||||
}
|
||||
|
||||
// IsSuccess returns true if the response status code is in the 2xx range.
|
||||
func (r *Response) IsSuccess() bool {
|
||||
return r.StatusCode() >= http.StatusOK && r.StatusCode() < http.StatusMultipleChoices
|
||||
}
|
||||
|
||||
// StatusCode returns the HTTP status code of the response.
|
||||
func (r *Response) StatusCode() int {
|
||||
return r.Raw.StatusCode
|
||||
}
|
||||
|
||||
// BodyCopy returns a copy of the response body as bytes.
|
||||
//
|
||||
// The returned slice remains valid even after calling Close().
|
||||
func (r *Response) BodyCopy() ([]byte, error) {
|
||||
body, err := r.UnsafeBody()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
copied := make([]byte, len(body))
|
||||
copy(copied, body)
|
||||
|
||||
return copied, nil
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package httpcli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Retryer defines the interface for retry logic.
|
||||
// Implementations control when and how many times to retry failed operations.
|
||||
type Retryer interface {
|
||||
Do(ctx context.Context, f func() error) error
|
||||
}
|
||||
|
||||
// RetryCondition is a function that determines whether to retry based on
|
||||
// the error and response. Returns nil if no retry is needed.
|
||||
type RetryCondition func(err error, response *Response) error
|
||||
|
||||
// retryOptions holds retry configuration for a request.
|
||||
type retryOptions struct {
|
||||
condition RetryCondition
|
||||
retrier Retryer
|
||||
}
|
||||
|
||||
// nolint:gochecknoglobals
|
||||
var (
|
||||
noRetries = &retryOptions{
|
||||
condition: func(err error, response *Response) error {
|
||||
return err
|
||||
},
|
||||
retrier: noRetryer{},
|
||||
}
|
||||
)
|
||||
|
||||
// noRetryer is a retryer that never retries.
|
||||
type noRetryer struct {
|
||||
}
|
||||
|
||||
// Do executes the function exactly once without retry logic.
|
||||
func (n noRetryer) Do(_ context.Context, f func() error) error {
|
||||
return f()
|
||||
}
|
||||
|
||||
// NoRetries returns a retry condition and retryer that disable retry behavior.
|
||||
//
|
||||
// nolint:ireturn
|
||||
func NoRetries() (RetryCondition, Retryer) {
|
||||
return noRetries.condition, noRetries.retrier
|
||||
}
|
||||
|
||||
// IfErrorOr5XXStatus returns a retry condition that retries on network errors
|
||||
// or 5xx status codes.
|
||||
func IfErrorOr5XXStatus() RetryCondition {
|
||||
return func(err error, response *Response) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if response.Raw.StatusCode >= http.StatusInternalServerError && response.Raw.StatusCode <= 599 {
|
||||
return fmt.Errorf("status code %d", response.Raw.StatusCode) // nolint:err113
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user