client

package
v1.9.14 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2024 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

HTTP клиент.

Компонент предоставляет готовый и настроенный http клиент. Реализует интерфейс Doer, который доступен в контейнере объектов.

type Doer interface {
	Client() *http.Client
	Do(request *http.Request) (*http.Response, error)
	Use(middlewares ...middleware.Func)
}
Объект конфигурации.
type Config struct {
	Timeout                   time.Duration
	MaxIdleConnections        uint16
	MaxIdleConnectionsPerHost uint16
	MaxConnectionsPerHost     uint16
	SecureVerify              bool
}

Описание полей:

Поле Описание Значение по умолчанию
Timeout Таймаут запроса, этот параметр может быть передан одним из 3-х методов:
- флаг командной строки --client.http.timeout
- переменная окружения CLIENT_HTTP_TIMEOUT
- значение в конфиг файле client.http.timeout
30s
MaxIdleConnections Максимальное общее количество открытых соединений, этот параметр может быть передан одним из 3-х методов:
- флаг командной строки --client.http.maximum.idle.connections
- переменная окружения CLIENT_HTTP_MAXIMUM_IDLE_CONNECTIONS
- значение в конфиг файле client.http.maximum.idle.connections
100
MaxIdleConnectionsPerHost Максимальное количество открытых соединений на хост, этот параметр может быть передан одним из 3-х методов:
- флаг командной строки --client.http.maximum.idle.host
- переменная окружения CLIENT_HTTP_MAXIMUM_IDLE_HOST
- значение в конфиг файле client.http.maximum.idle.host
10
MaxConnectionsPerHost Максимальное количество соединений на хост, этот параметр может быть передан одним из 3-х методов:
- флаг командной строки --client.http.maximum.connections
- переменная окружения CLIENT_HTTP_MAXIMUM_CONNECTIONS
- значение в конфиг файле client.http.maximum.connections
20
SecureVerify Если "true", будет проводиться проверка TLS сертификат, этот параметр может быть передан одним из 3-х методов:
- флаг командной строки --client.http.secure_verify
- переменная окружения CLIENT_HTTP_SECURE_VERIFY
- значение в конфиг файле client.http.secure_verify
false

Пакет предоставляет несколько готовых middleware, который добавляются автоматически:

  • RequestLogger - логирует информацию о запросе, метод запроса, урл запроса, код ответа и время выполнения запроса, либо ошибку;
  • RequestDuration - добавляет метрику по времени выполнения запроса;
  • TotalRequestCount - добавляет метрику по общему кол. запросов.
Дополнительные компоненты.
Метрики.

Метрики добавляются автоматически при добавлении middleware.

go_http_client_duration_seconds - время выполнения запроса. Доступные лейблы в метрике:

  • app - имя приложения;
  • host - хост запроса;
  • endpoint - конечная точка (путь) запроса.

go_http_client_requests_total - общее кол. запросов. Доступные лейблы в метрике:

  • app - имя приложения;
  • host - хост запроса;
  • endpoint - конечная точка (путь) запроса;
  • code - код ответа на запрос.

Documentation

Index

Constants

View Source
const (
	TimeoutFieldName                   = "client.http.timeout"
	MaxIdleConnectionsFieldName        = "client.http.maximum.idle.connections"
	MaxIdleConnectionsPerHostFieldName = "client.http.maximum.idle.host"
	MaxConnectionsPerHostFieldName     = "client.http.maximum.connections"
	SecureVerifyFieldName              = "client.http.secure_verify"

	TimeoutDefault                   = 30 * time.Second
	MaxIdleConnectionsDefault        = uint16(100)
	MaxIdleConnectionsPerHostDefault = uint16(10)
	MaxConnectionsPerHostDefault     = uint16(20)
	SecureVerifyDefault              = false
)

Variables

View Source
var Component = &app.Component{
	Dependencies: app.Components{
		logger.Component,
		configurator.Component,
		reConfiguration.Component,
	},
	Constructor: app.Constructor(func(container container.Container) error {
		return container.Provides(
			NewConfig,
			NewReConfigurationWithConfigurator,
			func(reConfiguration *ReConfiguration) Doer { return reConfiguration },
		)
	}),
	BindFlags: app.BindFlags(func(flagSet *pflag.FlagSet, container container.Container) error {
		return container.Invoke(func(config *Config) {
			flagSet.DurationVar(&config.Timeout, TimeoutFieldName, TimeoutDefault, "request timeout")
			flagSet.Uint16Var(&config.MaxIdleConnections, MaxIdleConnectionsFieldName, MaxIdleConnectionsDefault, "maximum total number of open connections")
			flagSet.Uint16Var(&config.MaxIdleConnectionsPerHost, MaxIdleConnectionsPerHostFieldName, MaxIdleConnectionsPerHostDefault, "maximum number of open connections per host")
			flagSet.Uint16Var(&config.MaxConnectionsPerHost, MaxConnectionsPerHostFieldName, MaxConnectionsPerHostDefault, "maximum number of connections per host")
			flagSet.BoolVar(&config.SecureVerify, SecureVerifyFieldName, SecureVerifyDefault, "if true, check the TLS certificate")
		})
	}),
	Run: app.Run(func(container container.Container) error {
		return container.Invoke(func(
			client *ReConfiguration,
			informer logger.Informer,
			reConfiguration reConfiguration.ReConfiguration,
			config *Config,
		) {
			reConfiguration.Registration(client)
			informer.Info("http.client: registration in the reConfigurator")
		})
	}),
}

Functions

This section is empty.

Types

type Client

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

func New

func New(config *Config, informer logger.Informer) *Client

func NewClient

func NewClient(client *http.Client, originalTransport *http.Transport) *Client

func NewWithConfigurator

func NewWithConfigurator(configurator configurator.Configurator, config *Config, informer logger.Informer) *Client

func (*Client) Client

func (client *Client) Client() *http.Client

func (*Client) Do

func (client *Client) Do(request *http.Request) (*http.Response, error)

func (*Client) Use

func (client *Client) Use(middlewares ...Middleware)

type Config

type Config struct {
	Timeout                   time.Duration
	MaxIdleConnections        uint16
	MaxIdleConnectionsPerHost uint16
	MaxConnectionsPerHost     uint16
	SecureVerify              bool
}

func Configuration

func Configuration(config *Config, configurator configurator.Configurator) *Config

func NewConfig

func NewConfig() *Config

type Doer

type Doer interface {
	Client() *http.Client
	Do(request *http.Request) (*http.Response, error)
	Use(middlewares ...Middleware)
}

type Middleware added in v1.8.12

type Middleware interface {
	Middleware(next http.RoundTripper) http.RoundTripper
}

type MiddlewareFunc added in v1.8.12

type MiddlewareFunc func(next http.RoundTripper) http.RoundTripper

func (MiddlewareFunc) Middleware added in v1.8.12

func (middleware MiddlewareFunc) Middleware(next http.RoundTripper) http.RoundTripper

type ReConfiguration

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

func NewReConfiguration

func NewReConfiguration(informer logger.Informer, config *Config) *ReConfiguration

func NewReConfigurationWithConfigurator

func NewReConfigurationWithConfigurator(informer logger.Informer, config *Config, configurator configurator.Configurator) *ReConfiguration

func (*ReConfiguration) Client

func (reConfiguration *ReConfiguration) Client() *http.Client

func (*ReConfiguration) Do

func (reConfiguration *ReConfiguration) Do(request *http.Request) (*http.Response, error)

func (*ReConfiguration) ReConfiguration

func (reConfiguration *ReConfiguration) ReConfiguration(configurator configurator.Configurator) error

func (*ReConfiguration) Use

func (reConfiguration *ReConfiguration) Use(middlewares ...Middleware)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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