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
|
||||
}
|
||||
}
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
# Package `httpclix`
|
||||
|
||||
Пакет `httpclix` предоставляет расширенный HTTP-клиент с балансировкой нагрузки, метриками, трейсингом и логированием.
|
||||
Интегрируется с системами мониторинга и трассировки, поддерживает гибкую настройку middleware.
|
||||
|
||||
## Types
|
||||
|
||||
### ClientBalancer
|
||||
|
||||
Структура для клиента со встроенным балансировщиком HTTP-запросов между несколькими хостами. Управляет подключениями,
|
||||
обновлением списка хостов и автоматическим добавлением схемы (HTTP/HTTPS).
|
||||
Расширяет [`httpcli.Client`](../httpcli/client.go) и использует пакет [`lb`](../../lb) для балансировки.
|
||||
|
||||
**Methods:**
|
||||
|
||||
Содержит все методы клиента-предшественника.
|
||||
|
||||
#### `NewClientBalancer(initialHosts []string, opts ...Option) *ClientBalancer`
|
||||
|
||||
Конструктор HTTP-клиента с балансировщиком. Принимает начальный список хостов и опции для настройки:
|
||||
|
||||
- `WithClientOptions(opts ...httpcli.Option) Option` – добавить опции для родительского клиента из пакета [
|
||||
`httpcli`](../httpcli).
|
||||
- `WithHttpsSchema() Option` – автоматически добавлять к хостам https схему, вместо http.
|
||||
- `WithClient(cli *http.Client) Option` – создание http-клиента на основе базового клиента из стандартной библиотеки
|
||||
`net/http`.
|
||||
|
||||
#### `(c *ClientBalancer) Upgrade(hosts []string)`
|
||||
|
||||
Обновляет список активных хостов. Автоматически добавляет схему, если она не указана.
|
||||
|
||||
### ClientTracer
|
||||
|
||||
Структура `ClientTracer` предоставляет инструменты для трейсинга HTTP-запросов, включая измерение времени выполнения
|
||||
ключевых этапов. Используется совместно с httptrace.ClientTrace для интеграции в HTTP-клиент.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewClientTracer(clientStorage *metrics.ClientStorage, endpoint string) *ClientTracer`
|
||||
|
||||
Создает трейсер для интеграции с httptrace.
|
||||
|
||||
#### `(cli *ClientTracer) ClientTrace() *httptrace.ClientTrace`
|
||||
|
||||
Создает и возвращает объект httptrace.ClientTrace с хуками для отслеживания этапов запроса:
|
||||
|
||||
- `DNSStart` – Засекает время начала DNS-запроса.
|
||||
- `DNSDone` – Рассчитывает длительность DNS-запроса и сохраняет в метрики через `clientStorage.ObserveDnsLookup`.
|
||||
- `ConnectStart` – Засекает начало установки TCP-соединения.
|
||||
- `ConnectDone` – Сохраняет длительность установки соединения через `clientStorage.ObserveConnEstablishment`.
|
||||
- `WroteHeaders` – Начало записи тела запроса (после отправки заголовков).
|
||||
- `WroteRequest` – Сохраняет длительность записи тела запроса через `clientStorage.ObserveRequestWriting`.
|
||||
- `GotFirstResponseByte` – Засекает получение первого байта ответа.
|
||||
|
||||
#### `(cli *ClientTracer) ResponseReceived()`
|
||||
|
||||
Вызывается при полном получении ответа. Рассчитывает длительность чтения ответа и сохраняет в метрики через
|
||||
`clientStorage.ObserveResponseReading`.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `Default(opts ...httpcli.Option) *httpcli.Client`
|
||||
|
||||
Создает клиент с предустановленными middleware:
|
||||
|
||||
- Добавление RequestId.
|
||||
- Сбор метрик через http_metrics.
|
||||
- Трейсинг запросов.
|
||||
|
||||
#### `DefaultWithBalancer(initialHosts []string, opts ...Option) *ClientBalancer`
|
||||
|
||||
Создает клиент-балансировщик с предустановленными middleware:
|
||||
|
||||
- Добавление RequestId.
|
||||
- Сбор метрик через http_metrics.
|
||||
- Трейсинг запросов.
|
||||
|
||||
#### `RequestId() httpcli.Middleware`
|
||||
|
||||
Добавляющая заголовок X-Request-Id к запросам middleware. Если requestId отсутствует в контексте — генерирует
|
||||
новый.
|
||||
|
||||
#### `Metrics(storage *http_metrics.ClientStorage) httpcli.Middleware`
|
||||
|
||||
Собирающая метрики middleware:
|
||||
|
||||
- Время выполнения запроса.
|
||||
- Статус-коды ответов.
|
||||
- Ошибки
|
||||
- Время DNS, установки соединения, записи тела и чтения ответа.
|
||||
|
||||
#### `Log(logger log.Logger) httpcli.Middleware`
|
||||
|
||||
Middleware для логирования запросов и ответов, включая заголовки и тело (опционально, можно настроить с помощью
|
||||
контекста).
|
||||
|
||||
####
|
||||
|
||||
`LogConfigToContext(ctx context.Context, logRequestBody bool, logResponseBody bool, opts ...LogOption) context.Context`
|
||||
|
||||
Данная функция добавляет в контекст настройки логирования для HTTP-запросов. Эти настройки определяют, какие данные (
|
||||
тело, заголовки, дампы) будут записаны в лог при обработке запроса и ответа.
|
||||
|
||||
Доступные опции:
|
||||
|
||||
- `LogDump(dumpRequest bool, dumpResponse bool) LogOption` – включение/выключение дампа запроса и ответа.
|
||||
- `LogHeaders(requestHeaders bool, responseHeaders bool) LogOption` – включение/выключение логирования заголовков
|
||||
запроса и ответа.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/httpclix"
|
||||
)
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func main() {
|
||||
/* client with metrics, traces & logging */
|
||||
cli := httpclix.Default()
|
||||
userList := make([]user, 0)
|
||||
|
||||
err := cli.Get("https://api.example.com/users").
|
||||
JsonResponseBody(&userList).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(context.Background())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Client with balancer
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/httpclix"
|
||||
)
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func main() {
|
||||
hosts := []string{"host1:8080", "host2:8080", "http://host2:8080"}
|
||||
cli := httpclix.NewClientBalancer(hosts, httpclix.WithHttpsSchema())
|
||||
|
||||
/* Requests are distributed between hosts */
|
||||
for i := range 5 {
|
||||
err := cli.Get("/data").
|
||||
JsonResponseBody(&userList).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(context.Background())
|
||||
/* some business logic */
|
||||
}
|
||||
|
||||
/* update host list */
|
||||
cli.Upgrade([]string{"new-host:8080"})
|
||||
}
|
||||
|
||||
```
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package httpclix
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
)
|
||||
|
||||
// Default creates a new Client with default middlewares for observability,
|
||||
// metrics, and request tracing.
|
||||
//
|
||||
// Additional options are applied after the default middlewares.
|
||||
func Default(opts ...httpcli.Option) *httpcli.Client {
|
||||
opts = append([]httpcli.Option{
|
||||
httpcli.WithMiddlewares(DefaultMiddlewares()...),
|
||||
}, opts...)
|
||||
return httpcli.New(opts...)
|
||||
}
|
||||
|
||||
// DefaultWithBalancer creates a new ClientBalancer with default middlewares
|
||||
// and load balancing across the provided hosts.
|
||||
//
|
||||
// Additional options are applied after the default middlewares.
|
||||
func DefaultWithBalancer(initialHosts []string, opts ...Option) *ClientBalancer {
|
||||
opts = append([]Option{
|
||||
WithClientOptions(
|
||||
httpcli.WithMiddlewares(DefaultMiddlewares()...),
|
||||
),
|
||||
}, opts...)
|
||||
return NewClientBalancer(initialHosts, opts...)
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
package httpclix
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/lb"
|
||||
)
|
||||
|
||||
const (
|
||||
httpsSchema = "https://"
|
||||
httpSchema = "http://"
|
||||
)
|
||||
|
||||
// ClientBalancer is an HTTP client that distributes requests across multiple
|
||||
// hosts using round-robin load balancing.
|
||||
//
|
||||
// It embeds httpcli.Client and extends it with host management functionality.
|
||||
type ClientBalancer struct {
|
||||
*httpcli.Client
|
||||
|
||||
hostManager *lb.RoundRobin
|
||||
schema string
|
||||
}
|
||||
|
||||
// NewClientBalancer creates a new ClientBalancer with the given initial hosts
|
||||
// and options.
|
||||
//
|
||||
// Hosts without a schema prefix automatically get http:// prepended.
|
||||
func NewClientBalancer(initialHosts []string, opts ...Option) *ClientBalancer {
|
||||
options := &clientBalancerOptions{
|
||||
cli: nil,
|
||||
clientOpts: nil,
|
||||
schema: httpSchema,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
initialHosts = addSchemaToHosts(options.schema, initialHosts)
|
||||
|
||||
return &ClientBalancer{
|
||||
Client: httpClient(options.cli, options.clientOpts...),
|
||||
hostManager: lb.NewRoundRobin(initialHosts),
|
||||
schema: options.schema,
|
||||
}
|
||||
}
|
||||
|
||||
// Post creates a new POST request builder for the given path.
|
||||
// The path is appended to the currently selected host.
|
||||
func (c *ClientBalancer) Post(method string) *httpcli.RequestBuilder {
|
||||
return httpcli.NewRequestBuilder(http.MethodPost, method, c.GlobalRequestConfig(), c.Execute)
|
||||
}
|
||||
|
||||
// Get creates a new GET request builder for the given path.
|
||||
// The path is appended to the currently selected host.
|
||||
func (c *ClientBalancer) Get(method string) *httpcli.RequestBuilder {
|
||||
return httpcli.NewRequestBuilder(http.MethodGet, method, c.GlobalRequestConfig(), c.Execute)
|
||||
}
|
||||
|
||||
// Put creates a new PUT request builder for the given path.
|
||||
// The path is appended to the currently selected host.
|
||||
func (c *ClientBalancer) Put(method string) *httpcli.RequestBuilder {
|
||||
return httpcli.NewRequestBuilder(http.MethodPut, method, c.GlobalRequestConfig(), c.Execute)
|
||||
}
|
||||
|
||||
// Delete creates a new DELETE request builder for the given path.
|
||||
// The path is appended to the currently selected host.
|
||||
func (c *ClientBalancer) Delete(method string) *httpcli.RequestBuilder {
|
||||
return httpcli.NewRequestBuilder(http.MethodDelete, method, c.GlobalRequestConfig(), c.Execute)
|
||||
}
|
||||
|
||||
// Patch creates a new PATCH request builder for the given path.
|
||||
// The path is appended to the currently selected host.
|
||||
func (c *ClientBalancer) Patch(method string) *httpcli.RequestBuilder {
|
||||
return httpcli.NewRequestBuilder(http.MethodPatch, method, c.GlobalRequestConfig(), c.Execute)
|
||||
}
|
||||
|
||||
// Execute sends an HTTP request using the provided builder and the load balancer.
|
||||
//
|
||||
// If GlobalRequestConfig.BaseUrl is set, the request is sent to that URL.
|
||||
// Otherwise, the next host from the round-robin balancer is selected and the
|
||||
// request path is appended to it.
|
||||
func (c *ClientBalancer) Execute(ctx context.Context, builder *httpcli.RequestBuilder) (*httpcli.Response, error) {
|
||||
if c.GlobalRequestConfig().BaseUrl != "" {
|
||||
return c.Client.Execute(ctx, builder)
|
||||
}
|
||||
|
||||
host, err := c.hostManager.Next()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "host manager next")
|
||||
}
|
||||
|
||||
return c.Client.Execute(ctx, builder.BaseUrl(host))
|
||||
}
|
||||
|
||||
// Upgrade replaces the current set of hosts with a new set.
|
||||
//
|
||||
// Hosts without a schema prefix automatically get the configured schema prepended.
|
||||
func (c *ClientBalancer) Upgrade(hosts []string) {
|
||||
hosts = addSchemaToHosts(c.schema, hosts)
|
||||
c.hostManager.Upgrade(hosts)
|
||||
}
|
||||
|
||||
// addSchemaToHosts prepends the schema to hosts that don't have one.
|
||||
func addSchemaToHosts(schema string, hosts []string) []string {
|
||||
for i, host := range hosts {
|
||||
shouldAddSchema := !strings.HasPrefix(host, httpSchema) && !strings.HasPrefix(host, httpsSchema)
|
||||
if shouldAddSchema {
|
||||
hosts[i] = schema + host
|
||||
}
|
||||
}
|
||||
return hosts
|
||||
}
|
||||
|
||||
// httpClient creates an httpcli.Client, using the provided client if non-nil,
|
||||
// otherwise creating a new one with the given options.
|
||||
func httpClient(cli *http.Client, opts ...httpcli.Option) *httpcli.Client {
|
||||
if cli == nil {
|
||||
return httpcli.New(opts...)
|
||||
}
|
||||
return httpcli.NewWithClient(cli, opts...)
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package httpclix
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
)
|
||||
|
||||
// clientBalancerOptions holds configuration options for ClientBalancer.
|
||||
type clientBalancerOptions struct {
|
||||
cli *http.Client
|
||||
clientOpts []httpcli.Option
|
||||
schema string
|
||||
}
|
||||
|
||||
// Option is a function that configures a ClientBalancer.
|
||||
type Option func(c *clientBalancerOptions)
|
||||
|
||||
// WithClientOptions appends the given client options to the ClientBalancer.
|
||||
func WithClientOptions(opts ...httpcli.Option) Option {
|
||||
return func(c *clientBalancerOptions) {
|
||||
c.clientOpts = append(c.clientOpts, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
// WithHttpsSchema configures the ClientBalancer to use https:// as the URL schema.
|
||||
func WithHttpsSchema() Option {
|
||||
return func(c *clientBalancerOptions) {
|
||||
c.schema = httpsSchema
|
||||
}
|
||||
}
|
||||
|
||||
// WithClient sets a custom http.Client for the ClientBalancer.
|
||||
func WithClient(cli *http.Client) Option {
|
||||
return func(c *clientBalancerOptions) {
|
||||
c.cli = cli
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
// Package httpclix provides extended HTTP client functionality including
|
||||
// load balancing, logging, and observability middleware.
|
||||
//
|
||||
// This package builds on httpcli to provide production-ready HTTP clients
|
||||
// with built-in support for request tracing, metrics, and logging.
|
||||
package httpclix
|
||||
+312
@@ -0,0 +1,312 @@
|
||||
package httpclix
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// logConfig holds configuration for the logging middleware.
|
||||
type logConfig struct {
|
||||
LogRequestBody bool
|
||||
LogResponseBody bool
|
||||
|
||||
LogDumpRequest bool
|
||||
LogDumpResponse bool
|
||||
|
||||
LogHeadersRequest bool
|
||||
LogHeadersResponse bool
|
||||
|
||||
CombinedLog bool
|
||||
}
|
||||
|
||||
// LogOption is a function that configures log behavior.
|
||||
type LogOption func(*logConfig)
|
||||
|
||||
// LogDump enables raw HTTP request/response dumping.
|
||||
// When enabled, the full HTTP request and/or response are logged including headers and body.
|
||||
func LogDump(dumpRequest bool, dumpResponse bool) LogOption {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.LogDumpRequest = dumpRequest
|
||||
cfg.LogDumpResponse = dumpResponse
|
||||
}
|
||||
}
|
||||
|
||||
// LogHeaders enables logging of HTTP request and response headers.
|
||||
func LogHeaders(requestHeaders bool, responseHeaders bool) LogOption {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.LogHeadersRequest = requestHeaders
|
||||
cfg.LogHeadersResponse = responseHeaders
|
||||
}
|
||||
}
|
||||
|
||||
// LogCombined enables combined logging mode where all fields are logged in a single
|
||||
// log entry instead of separate request and response entries.
|
||||
func LogCombined(combinedLog bool) LogOption {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.CombinedLog = combinedLog
|
||||
}
|
||||
}
|
||||
|
||||
// logConfigContextKey is the context key for per-request log configuration.
|
||||
type logConfigContextKey struct{}
|
||||
|
||||
var logConfigContextKeyValue = logConfigContextKey{} // nolint:gochecknoglobals
|
||||
|
||||
// LogConfigToContext creates a new context with per-request logging configuration.
|
||||
//
|
||||
// This allows overriding the default log behavior for specific requests.
|
||||
func LogConfigToContext(
|
||||
ctx context.Context,
|
||||
logRequestBody bool,
|
||||
logResponseBody bool,
|
||||
opts ...LogOption,
|
||||
) context.Context {
|
||||
cfg := logConfig{
|
||||
LogRequestBody: logRequestBody,
|
||||
LogResponseBody: logResponseBody,
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(&cfg)
|
||||
}
|
||||
return context.WithValue(ctx, logConfigContextKeyValue, cfg)
|
||||
}
|
||||
|
||||
// Log creates a middleware that logs HTTP requests and responses with
|
||||
// sensible defaults (request body and response body enabled).
|
||||
//
|
||||
// All logs are at Debug level unless the response has an error status code.
|
||||
func Log(logger log.Logger) httpcli.Middleware {
|
||||
cfg := &logConfig{
|
||||
LogRequestBody: true,
|
||||
LogResponseBody: true,
|
||||
CombinedLog: false,
|
||||
}
|
||||
|
||||
return dynamicLogMiddleware(logger, cfg)
|
||||
}
|
||||
|
||||
// LogWithOptions creates a middleware that logs HTTP requests and responses
|
||||
// with custom configuration.
|
||||
//
|
||||
// By default, no body content is logged. Use LogDump, LogHeaders, or other
|
||||
// options to enable specific logging features.
|
||||
func LogWithOptions(logger log.Logger, opts ...LogOption) httpcli.Middleware {
|
||||
cfg := &logConfig{
|
||||
LogRequestBody: false,
|
||||
LogResponseBody: false,
|
||||
CombinedLog: false,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(cfg)
|
||||
}
|
||||
|
||||
return dynamicLogMiddleware(logger, cfg)
|
||||
}
|
||||
|
||||
// dynamicLogMiddleware creates a middleware that logs HTTP requests and responses
|
||||
// using the provided logger and configuration.
|
||||
//
|
||||
// Per-request configuration from context is merged with the default configuration.
|
||||
func dynamicLogMiddleware(logger log.Logger, defaultCfg *logConfig) httpcli.Middleware {
|
||||
return func(next httpcli.RoundTripper) httpcli.RoundTripper {
|
||||
return httpcli.RoundTripperFunc(func(ctx context.Context, request *httpcli.Request) (*httpcli.Response, error) {
|
||||
config := mergeLogConfig(ctx, defaultCfg)
|
||||
|
||||
if config.CombinedLog {
|
||||
return combinedLogMiddlewareHandler(ctx, logger, config, next, request)
|
||||
}
|
||||
return logMiddlewareHandler(ctx, logger, config, next, request)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// logMiddlewareHandler handles logging for HTTP requests and responses separately.
|
||||
//
|
||||
// Logs the request before execution and the response after execution.
|
||||
func logMiddlewareHandler(
|
||||
ctx context.Context,
|
||||
logger log.Logger,
|
||||
config logConfig,
|
||||
next httpcli.RoundTripper,
|
||||
request *httpcli.Request,
|
||||
) (*httpcli.Response, error) {
|
||||
requestFields := []log.Field{
|
||||
log.String("method", request.Raw.Method),
|
||||
log.String("url", request.Raw.URL.String()),
|
||||
}
|
||||
|
||||
if config.LogRequestBody {
|
||||
requestFields = append(requestFields, log.ByteString("requestBody", request.Body()))
|
||||
}
|
||||
|
||||
logger.Debug(ctx, "http client: request", requestFields...)
|
||||
|
||||
now := time.Now()
|
||||
resp, err := next.RoundTrip(ctx, request)
|
||||
|
||||
var responseFields []log.Field
|
||||
|
||||
if config.LogHeadersRequest {
|
||||
headers, _ := json.Marshal(request.Raw.Header)
|
||||
responseFields = append(responseFields, log.ByteString("requestHeaders", headers))
|
||||
}
|
||||
|
||||
if config.LogDumpRequest {
|
||||
request.Raw.Body = io.NopCloser(bytes.NewBuffer(request.Body()))
|
||||
dumpReq, _ := httputil.DumpRequestOut(request.Raw, true)
|
||||
responseFields = append(responseFields, log.ByteString("requestDump", dumpReq))
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
responseFields = append(responseFields,
|
||||
log.Any("error", err),
|
||||
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
|
||||
)
|
||||
|
||||
logger.Debug(ctx, "http client: response with error", responseFields...)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
responseFields = append(responseFields, log.Int("statusCode", resp.StatusCode()))
|
||||
|
||||
if config.LogDumpResponse {
|
||||
dumpResp, _ := httputil.DumpResponse(resp.Raw, true)
|
||||
responseFields = append(responseFields, log.ByteString("responseDump", dumpResp))
|
||||
}
|
||||
|
||||
if config.LogHeadersResponse {
|
||||
headers, _ := json.Marshal(resp.Raw.Header)
|
||||
responseFields = append(responseFields, log.ByteString("responseHeaders", headers))
|
||||
}
|
||||
|
||||
if config.LogResponseBody {
|
||||
responseBody, _ := resp.UnsafeBody()
|
||||
responseFields = append(responseFields, log.ByteString("responseBody", responseBody))
|
||||
}
|
||||
|
||||
responseFields = append(responseFields, log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()))
|
||||
|
||||
logResponseByStatusCode(ctx, logger, responseFields, resp)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// combinedLogMiddlewareHandler handles logging for HTTP requests and responses
|
||||
// in a single combined log entry.
|
||||
func combinedLogMiddlewareHandler(
|
||||
ctx context.Context,
|
||||
logger log.Logger,
|
||||
config logConfig,
|
||||
next httpcli.RoundTripper,
|
||||
request *httpcli.Request,
|
||||
) (*httpcli.Response, error) {
|
||||
var logFields []log.Field
|
||||
logFields = append(logFields,
|
||||
log.String("method", request.Raw.Method),
|
||||
log.String("url", request.Raw.URL.String()),
|
||||
)
|
||||
|
||||
if config.LogRequestBody {
|
||||
logFields = append(logFields, log.ByteString("requestBody", request.Body()))
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
resp, err := next.RoundTrip(ctx, request)
|
||||
|
||||
if config.LogHeadersRequest {
|
||||
headers, _ := json.Marshal(request.Raw.Header)
|
||||
logFields = append(logFields, log.ByteString("requestHeaders", headers))
|
||||
}
|
||||
|
||||
if config.LogDumpRequest {
|
||||
request.Raw.Body = io.NopCloser(bytes.NewBuffer(request.Body()))
|
||||
dumpReq, _ := httputil.DumpRequestOut(request.Raw, true)
|
||||
logFields = append(logFields, log.ByteString("requestDump", dumpReq))
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logFields = append(logFields,
|
||||
log.Any("error", err),
|
||||
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
|
||||
)
|
||||
|
||||
logger.Debug(ctx, "http client: log with error", logFields...)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
logFields = append(logFields, log.Int("statusCode", resp.StatusCode()))
|
||||
|
||||
if config.LogDumpResponse {
|
||||
dumpResp, _ := httputil.DumpResponse(resp.Raw, true)
|
||||
logFields = append(logFields, log.ByteString("responseDump", dumpResp))
|
||||
}
|
||||
|
||||
if config.LogHeadersResponse {
|
||||
headers, _ := json.Marshal(resp.Raw.Header)
|
||||
logFields = append(logFields, log.ByteString("responseHeaders", headers))
|
||||
}
|
||||
|
||||
if config.LogResponseBody {
|
||||
responseBody, _ := resp.UnsafeBody()
|
||||
logFields = append(logFields, log.ByteString("responseBody", responseBody))
|
||||
}
|
||||
|
||||
logFields = append(logFields, log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()))
|
||||
|
||||
logCombinedByStatusCode(ctx, logger, logFields, resp)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// mergeLogConfig merges per-request log configuration from context with defaults.
|
||||
//
|
||||
// Returns the default configuration if no per-request configuration is found.
|
||||
func mergeLogConfig(ctx context.Context, defaultCfg *logConfig) logConfig {
|
||||
configFromContext, ok := ctx.Value(logConfigContextKeyValue).(logConfig)
|
||||
if !ok {
|
||||
return *defaultCfg
|
||||
}
|
||||
|
||||
return configFromContext
|
||||
}
|
||||
|
||||
// logResponseByStatusCode logs response information with appropriate log level
|
||||
// based on the HTTP status code.
|
||||
//
|
||||
// 5xx errors are logged as Error, 4xx as Warn, and others as Debug.
|
||||
func logResponseByStatusCode(ctx context.Context, logger log.Logger, responseFields []log.Field, resp *httpcli.Response) {
|
||||
switch {
|
||||
case resp.StatusCode() >= http.StatusInternalServerError:
|
||||
logger.Error(ctx, "http client: response", responseFields...)
|
||||
case resp.StatusCode() >= http.StatusBadRequest:
|
||||
logger.Warn(ctx, "http client: response", responseFields...)
|
||||
default:
|
||||
logger.Debug(ctx, "http client: response", responseFields...)
|
||||
}
|
||||
}
|
||||
|
||||
// logCombinedByStatusCode logs combined request/response information with
|
||||
// appropriate log level based on the HTTP status code.
|
||||
//
|
||||
// 5xx errors are logged as Error, 4xx as Warn, and others as Debug.
|
||||
func logCombinedByStatusCode(ctx context.Context, logger log.Logger, logFields []log.Field, resp *httpcli.Response) {
|
||||
switch {
|
||||
case resp.StatusCode() >= http.StatusInternalServerError:
|
||||
logger.Error(ctx, "http client: log", logFields...)
|
||||
case resp.StatusCode() >= http.StatusBadRequest:
|
||||
logger.Warn(ctx, "http client: log", logFields...)
|
||||
default:
|
||||
logger.Debug(ctx, "http client: log", logFields...)
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package httpclix
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http/httptrace"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/metrics"
|
||||
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
||||
"github.com/txix-open/isp-kit/observability/tracing/http/client_tracing"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
)
|
||||
|
||||
// DefaultMiddlewares returns a slice of middlewares for production use,
|
||||
// including request ID propagation, metrics collection, and distributed tracing.
|
||||
func DefaultMiddlewares() []httpcli.Middleware {
|
||||
return []httpcli.Middleware{
|
||||
RequestId(),
|
||||
Metrics(http_metrics.NewClientStorage(metrics.DefaultRegistry)),
|
||||
client_tracing.NewConfig().Middleware(),
|
||||
}
|
||||
}
|
||||
|
||||
// RequestId is a middleware that ensures every request has a unique ID.
|
||||
//
|
||||
// If a request ID already exists in the context, it is used. Otherwise,
|
||||
// a new ID is generated and added to the request headers.
|
||||
func RequestId() httpcli.Middleware {
|
||||
return func(next httpcli.RoundTripper) httpcli.RoundTripper {
|
||||
return httpcli.RoundTripperFunc(func(ctx context.Context, request *httpcli.Request) (*httpcli.Response, error) {
|
||||
requestId := requestid.FromContext(ctx)
|
||||
if requestId == "" {
|
||||
requestId = requestid.Next()
|
||||
}
|
||||
|
||||
request.Raw.Header.Set(requestid.Header, requestId)
|
||||
return next.RoundTrip(ctx, request)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Metrics is a middleware that collects HTTP client metrics including
|
||||
// request duration, status codes, and errors.
|
||||
//
|
||||
// The endpoint must be set in the context using http_metrics.ClientEndpoint.
|
||||
//
|
||||
// DNS lookup, connection establishment, request writing, and response reading
|
||||
// times are also observed when available.
|
||||
func Metrics(storage *http_metrics.ClientStorage) httpcli.Middleware {
|
||||
return func(next httpcli.RoundTripper) httpcli.RoundTripper {
|
||||
return httpcli.RoundTripperFunc(func(ctx context.Context, request *httpcli.Request) (*httpcli.Response, error) {
|
||||
endpoint := http_metrics.ClientEndpoint(ctx)
|
||||
if endpoint == "" {
|
||||
return next.RoundTrip(ctx, request)
|
||||
}
|
||||
|
||||
clientTracer := NewClientTracer(storage, endpoint)
|
||||
ctx = httptrace.WithClientTrace(ctx, clientTracer.ClientTrace())
|
||||
|
||||
ctx = context.WithValue(ctx, httpcli.ReadingResponseMetricHookKey, clientTracer.ResponseReceived)
|
||||
request.Raw = request.Raw.WithContext(ctx)
|
||||
|
||||
start := time.Now()
|
||||
resp, err := next.RoundTrip(ctx, request)
|
||||
|
||||
storage.ObserveDuration(endpoint, time.Since(start))
|
||||
|
||||
if resp != nil && resp.Raw != nil {
|
||||
storage.CountStatusCode(endpoint, resp.StatusCode())
|
||||
}
|
||||
if err != nil {
|
||||
storage.CountError(endpoint, err)
|
||||
}
|
||||
|
||||
return resp, err
|
||||
})
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package httpclix
|
||||
|
||||
import (
|
||||
metrics "github.com/txix-open/isp-kit/metrics/http_metrics"
|
||||
"net/http/httptrace"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ClientTracer collects detailed timing information for HTTP client operations.
|
||||
//
|
||||
// It implements the httptrace.ClientTrace interface to measure DNS lookup,
|
||||
// connection establishment, request writing, and response reading durations.
|
||||
type ClientTracer struct {
|
||||
clientStorage *metrics.ClientStorage
|
||||
connEstablishmentStartTime time.Time
|
||||
dnsStartTime time.Time
|
||||
requestWritingStartTime time.Time
|
||||
responseReadingStartTime time.Time
|
||||
endpoint string
|
||||
}
|
||||
|
||||
// NewClientTracer creates a new ClientTracer for the given endpoint.
|
||||
func NewClientTracer(clientStorage *metrics.ClientStorage, endpoint string) *ClientTracer {
|
||||
return &ClientTracer{
|
||||
clientStorage: clientStorage,
|
||||
endpoint: endpoint,
|
||||
}
|
||||
}
|
||||
|
||||
// ClientTrace returns an httptrace.ClientTrace that records timing metrics
|
||||
// for the various phases of an HTTP request.
|
||||
func (cli *ClientTracer) ClientTrace() *httptrace.ClientTrace {
|
||||
tracingCli := httptrace.ClientTrace{
|
||||
DNSStart: func(info httptrace.DNSStartInfo) {
|
||||
cli.dnsStartTime = time.Now()
|
||||
},
|
||||
DNSDone: func(info httptrace.DNSDoneInfo) {
|
||||
if cli.dnsStartTime.IsZero() {
|
||||
return
|
||||
}
|
||||
dnsLookupDur := time.Since(cli.dnsStartTime)
|
||||
cli.clientStorage.ObserveDnsLookup(cli.endpoint, dnsLookupDur)
|
||||
},
|
||||
|
||||
ConnectStart: func(network string, addr string) {
|
||||
cli.connEstablishmentStartTime = time.Now()
|
||||
},
|
||||
ConnectDone: func(network, addr string, err error) {
|
||||
if cli.connEstablishmentStartTime.IsZero() {
|
||||
return
|
||||
}
|
||||
connEstablishmentDur := time.Since(cli.connEstablishmentStartTime)
|
||||
cli.clientStorage.ObserveConnEstablishment(cli.endpoint, connEstablishmentDur)
|
||||
},
|
||||
|
||||
// starting to write body
|
||||
WroteHeaders: func() {
|
||||
cli.requestWritingStartTime = time.Now()
|
||||
},
|
||||
WroteRequest: func(info httptrace.WroteRequestInfo) {
|
||||
if cli.requestWritingStartTime.IsZero() {
|
||||
return
|
||||
}
|
||||
requestWritingDur := time.Since(cli.requestWritingStartTime)
|
||||
cli.clientStorage.ObserveRequestWriting(cli.endpoint, requestWritingDur)
|
||||
},
|
||||
|
||||
// response writing started
|
||||
GotFirstResponseByte: func() {
|
||||
cli.responseReadingStartTime = time.Now()
|
||||
},
|
||||
}
|
||||
return &tracingCli
|
||||
}
|
||||
|
||||
// ResponseReceived is called when the response body has been fully read.
|
||||
//
|
||||
// Records the duration of response reading.
|
||||
func (cli *ClientTracer) ResponseReceived() {
|
||||
if cli.responseReadingStartTime.IsZero() {
|
||||
return
|
||||
}
|
||||
|
||||
respReadingDur := time.Since(cli.responseReadingStartTime)
|
||||
cli.clientStorage.ObserveResponseReading(cli.endpoint, respReadingDur)
|
||||
}
|
||||
Reference in new issue
Block a user