httpclix

package
v1.67.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 17 Imported by: 0

README

Package httpclix

Пакет httpclix предоставляет расширенный HTTP-клиент с балансировкой нагрузки, метриками, трейсингом и логированием. Интегрируется с системами мониторинга и трассировки, поддерживает гибкую настройку middleware.

Types

ClientBalancer

Структура для клиента со встроенным балансировщиком HTTP-запросов между несколькими хостами. Управляет подключениями, обновлением списка хостов и автоматическим добавлением схемы (HTTP/HTTPS). Расширяет httpcli.Client и использует пакет lb для балансировки.

Methods:

Содержит все методы клиента-предшественника.

NewClientBalancer(initialHosts []string, opts ...Option) *ClientBalancer

Конструктор HTTP-клиента с балансировщиком. Принимает начальный список хостов и опции для настройки:

  • WithClientOptions(opts ...httpcli.Option) Option – добавить опции для родительского клиента из пакета 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
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
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"})
}

Documentation

Overview

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.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Default

func Default(opts ...httpcli.Option) *httpcli.Client

Default creates a new Client with default middlewares for observability, metrics, and request tracing.

Additional options are applied after the default middlewares.

func DefaultMiddlewares added in v1.45.0

func DefaultMiddlewares() []httpcli.Middleware

DefaultMiddlewares returns a slice of middlewares for production use, including request ID propagation, metrics collection, and distributed tracing.

func Log

func Log(logger log.Logger) httpcli.Middleware

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 LogConfigToContext

func LogConfigToContext(
	ctx context.Context,
	logRequestBody bool,
	logResponseBody bool,
	opts ...LogOption,
) context.Context

LogConfigToContext creates a new context with per-request logging configuration.

This allows overriding the default log behavior for specific requests.

func LogWithOptions added in v1.66.3

func LogWithOptions(logger log.Logger, opts ...LogOption) httpcli.Middleware

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 Metrics

func Metrics(storage *http_metrics.ClientStorage) httpcli.Middleware

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 RequestId

func RequestId() httpcli.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.

Types

type ClientBalancer added in v1.45.0

type ClientBalancer struct {
	*httpcli.Client
	// contains filtered or unexported fields
}

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.

func DefaultWithBalancer added in v1.45.0

func DefaultWithBalancer(initialHosts []string, opts ...Option) *ClientBalancer

DefaultWithBalancer creates a new ClientBalancer with default middlewares and load balancing across the provided hosts.

Additional options are applied after the default middlewares.

func NewClientBalancer added in v1.45.0

func NewClientBalancer(initialHosts []string, opts ...Option) *ClientBalancer

NewClientBalancer creates a new ClientBalancer with the given initial hosts and options.

Hosts without a schema prefix automatically get http:// prepended.

func (*ClientBalancer) Delete added in v1.45.0

func (c *ClientBalancer) Delete(method string) *httpcli.RequestBuilder

Delete creates a new DELETE request builder for the given path. The path is appended to the currently selected host.

func (*ClientBalancer) Execute added in v1.45.0

func (c *ClientBalancer) Execute(ctx context.Context, builder *httpcli.RequestBuilder) (*httpcli.Response, error)

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 (*ClientBalancer) Get added in v1.45.0

func (c *ClientBalancer) Get(method string) *httpcli.RequestBuilder

Get creates a new GET request builder for the given path. The path is appended to the currently selected host.

func (*ClientBalancer) Patch added in v1.45.0

func (c *ClientBalancer) Patch(method string) *httpcli.RequestBuilder

Patch creates a new PATCH request builder for the given path. The path is appended to the currently selected host.

func (*ClientBalancer) Post added in v1.45.0

func (c *ClientBalancer) Post(method string) *httpcli.RequestBuilder

Post creates a new POST request builder for the given path. The path is appended to the currently selected host.

func (*ClientBalancer) Put added in v1.45.0

func (c *ClientBalancer) Put(method string) *httpcli.RequestBuilder

Put creates a new PUT request builder for the given path. The path is appended to the currently selected host.

func (*ClientBalancer) Upgrade added in v1.45.0

func (c *ClientBalancer) Upgrade(hosts []string)

Upgrade replaces the current set of hosts with a new set.

Hosts without a schema prefix automatically get the configured schema prepended.

type ClientTracer added in v1.38.0

type ClientTracer struct {
	// contains filtered or unexported fields
}

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.

func NewClientTracer added in v1.38.0

func NewClientTracer(clientStorage *metrics.ClientStorage, endpoint string) *ClientTracer

NewClientTracer creates a new ClientTracer for the given endpoint.

func (*ClientTracer) ClientTrace added in v1.38.0

func (cli *ClientTracer) ClientTrace() *httptrace.ClientTrace

ClientTrace returns an httptrace.ClientTrace that records timing metrics for the various phases of an HTTP request.

func (*ClientTracer) ResponseReceived added in v1.38.0

func (cli *ClientTracer) ResponseReceived()

ResponseReceived is called when the response body has been fully read.

Records the duration of response reading.

type LogOption added in v1.36.0

type LogOption func(*logConfig)

LogOption is a function that configures log behavior.

func LogCombined added in v1.66.3

func LogCombined(combinedLog bool) LogOption

LogCombined enables combined logging mode where all fields are logged in a single log entry instead of separate request and response entries.

func LogDump added in v1.36.0

func LogDump(dumpRequest bool, dumpResponse bool) LogOption

LogDump enables raw HTTP request/response dumping. When enabled, the full HTTP request and/or response are logged including headers and body.

func LogHeaders added in v1.36.0

func LogHeaders(requestHeaders bool, responseHeaders bool) LogOption

LogHeaders enables logging of HTTP request and response headers.

type Option added in v1.45.0

type Option func(c *clientBalancerOptions)

Option is a function that configures a ClientBalancer.

func WithClient added in v1.45.0

func WithClient(cli *http.Client) Option

WithClient sets a custom http.Client for the ClientBalancer.

func WithClientOptions added in v1.45.0

func WithClientOptions(opts ...httpcli.Option) Option

WithClientOptions appends the given client options to the ClientBalancer.

func WithHttpsSchema added in v1.45.0

func WithHttpsSchema() Option

WithHttpsSchema configures the ClientBalancer to use https:// as the URL schema.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL