http_client

package module
v1.0.0-rc1 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2026 License: MIT Imports: 8 Imported by: 0

README

Compogo HTTP Client

Go Reference

HTTP-клиент с поддержкой middleware для фреймворка Compogo.

Предоставляет:

  • Настраиваемый HTTP-клиент (таймауты, пул соединений, DNS)
  • Middleware для аутентификации (Basic Auth, Token Auth)
  • Логирование запросов и ответов
  • Метрики Prometheus (количество запросов, длительность)
  • Интеграцию с Compogo через компоненты

Установка

go get github.com/Compogo/http_client
Быстрый старт
package main

import (
    "github.com/Compogo/compogo"
    "github.com/Compogo/http_client"
    "github.com/Compogo/http_client/middleware/logger"
)

func main() {
    app := compogo.NewApp("myapp",
        compogo.WithComponents(&http_client.Component),
        compogo.WithComponents(&logger.AllLoggersComponent),
    )

    // Использование клиента
    app.AddComponents(&compogo.Component{
        Name: "my_service",
        Init: compogo.StepFunc(func(container compogo.Container) error {
            return container.Invoke(func(doer http_client.Doer) error {
                req, _ := http.NewRequest("GET", "https://api.example.com/users", nil)
                resp, err := doer.Do(req)
                // ...
                return nil
            })
        }),
    })

    if err := app.Serve(); err != nil {
        panic(err)
    }
}

Конфигурация

Флаги командной строки
# Таймаут запроса
--client.http.timeout=30s

# Настройки пула соединений
--client.http.maximum.idle.connections=100
--client.http.maximum.idle.host=10
--client.http.maximum.connections=20

# TLS (по умолчанию проверка включена)
--client.http.secure_verify=false

# Кастомный DNS-резолвер
--client.http.resolver.dns=8.8.8.8:53
Конфигурация через код
type Config struct {
    Timeout                   time.Duration
    MaxIdleConnections        uint16
    MaxIdleConnectionsPerHost uint16
    MaxConnectionsPerHost     uint16
    SecureVerify              bool
    DNS                       string
}

Middleware

Аутентификация
Basic Auth
import "github.com/Compogo/http_client/middleware/base"

// Подключение компонента
app.AddComponents(&base.Component)

// Настройка через флаг
// --client.http.auth.base.cred=admin:password
Token Auth
import "github.com/Compogo/http_client/middleware/token"

// Подключение компонента
app.AddComponents(&token.Component)

// Настройка через флаги
// --client.http.auth.token.token=abc123
// --client.http.auth.token.header=X-Auth-Token
Логирование
import "github.com/Compogo/http_client/middleware/logger"

// Только запросы
app.AddComponents(&logger.RequestLoggerComponent)

// Только ответы
app.AddComponents(&logger.ResponseLoggerComponent)

// Оба
app.AddComponents(&logger.AllLoggersComponent)
Уровни логирования:
  • Debug — тело запроса/ответа, заголовки
  • Info — метод, URL, статус, длительность
  • Warn — ошибки запроса
Метрики Prometheus
С разбивкой по эндпоинтам
import "github.com/Compogo/http_client/middleware/metric/by_endpoint"

// Подключение
app.AddComponents(&by_endpoint.AllMetricsComponent)

// Метрики:
// compogo_http_client_duration_seconds{app="myapp", host="api.example.com", endpoint="/users"}
// compogo_http_client_requests_total{app="myapp", code="200", host="api.example.com", endpoint="/users"}
Без разбивки по эндпоинтам
import "github.com/Compogo/http_client/middleware/metric/no_endpoint"

// Подключение
app.AddComponents(&no_endpoint.AllMetricsComponent)

// Метрики:
// compogo_http_client_duration_seconds{app="myapp", host="api.example.com"}
// compogo_http_client_requests_total{app="myapp", code="200", host="api.example.com"}

Зависимости

  • Compogo — основной фреймворк
  • Prometheus — метрики (опционально)

Лицензия

MIT License

Copyright (c) 2026 Compogo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Documentation

Index

Constants

View Source
const (
	// TimeoutFieldName таймаут запроса
	TimeoutFieldName = "client.http.timeout"

	// MaxIdleConnectionsFieldName общее количество простаивающих соединений
	MaxIdleConnectionsFieldName = "client.http.maximum.idle.connections"

	// MaxIdleConnectionsPerHostFieldName простаивающие соединения на хост
	MaxIdleConnectionsPerHostFieldName = "client.http.maximum.idle.host"

	// MaxConnectionsPerHostFieldName всего соединений на хост
	MaxConnectionsPerHostFieldName = "client.http.maximum.connections"

	// SecureVerifyFieldName проверка TLS сертификата
	SecureVerifyFieldName = "client.http.secure_verify"

	// ResolverDNSFieldName DNS-сервер для разрешения
	ResolverDNSFieldName = "client.http.resolver.dns"
)

Variables

View Source
var (
	TimeoutDefault                   = 30 * time.Second
	MaxIdleConnectionsDefault        = uint16(100)
	MaxIdleConnectionsPerHostDefault = uint16(10)
	MaxConnectionsPerHostDefault     = uint16(20)
	SecureVerifyDefault              = true
)
View Source
var Component = compogo.Component{
	Name: "http.client",
	Init: compogo.StepFunc(func(container compogo.Container) error {
		return container.Provides(
			NewConfig,
			NewDecorator,
			func(decorator *Decorator) Doer { return decorator },
		)
	}),
	BindFlags: compogo.BindFlags(func(flagSet flag.FlagSet, container compogo.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")
			flagSet.StringVar(&config.DNS, ResolverDNSFieldName, "", "If specified, attempts to resolve domain names through the specified DNS server.")
		})
	}),
	Configuration: compogo.StepFunc(func(container compogo.Container) error {
		return container.Invoke(Configuration)
	}),
	PreExecute: compogo.StepFunc(func(container compogo.Container) error {
		return container.Invoke(func(config *Config, logger compogo.Logger) {
			logger = logger.GetLogger("http").GetLogger("client")

			logger.Infof("timeout - %s", config.Timeout)
			logger.Infof("maxIdleConnections - %d", config.MaxIdleConnections)
			logger.Infof("maxIdleConnectionsPerHost - %d", config.MaxIdleConnectionsPerHost)
			logger.Infof("maxConnectionsPerHost - %d", config.MaxConnectionsPerHost)
			logger.Infof("tls secure verify - %s", strconv.FormatBool(config.SecureVerify))

			if config.DNS != "" {
				logger.Infof("dns - %s", config.DNS)
			}
		})
	}),
}

Component — компонент HTTP-клиента для Compogo. Регистрирует конфигурацию и клиент в DI-контейнере.

Functions

This section is empty.

Types

type Config

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

Config содержит конфигурацию HTTP-клиента.

func Configuration

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

Configuration загружает конфигурацию из Configurator. Если значения не заданы, устанавливаются значения по умолчанию.

func NewConfig

func NewConfig() *Config

NewConfig создаёт новую конфигурацию.

type Decorator

type Decorator struct {
	*http.Client
}

Decorator — обёртка над http.Client с поддержкой middleware. Позволяет добавлять middleware через Use().

func NewDecorator

func NewDecorator(config *Config) *Decorator

NewDecorator создаёт новый HTTP-клиент с конфигурацией. Настраивает:

  • Таймауты
  • Пул соединений (MaxIdleConns, MaxIdleConnsPerHost, MaxConnsPerHost)
  • TLS (возможность отключить проверку сертификатов)
  • Кастомный DNS-резолвер

func (*Decorator) Use

func (d *Decorator) Use(middlewares ...Middleware)

Use добавляет middleware в клиент. Middleware оборачивают Transport в цепочку обработки.

type Doer

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

Doer определяет интерфейс для выполнения HTTP-запросов. Расширяет стандартный http.Client методом Use для добавления middleware.

type Middleware

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

Middleware — интерфейс для обёртки http.RoundTripper. Позволяет добавлять логирование, аутентификацию, метрики и т.д.

type MiddlewareFunc

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

MiddlewareFunc — функциональный адаптер для Middleware.

func (MiddlewareFunc) Middleware

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

Middleware реализует интерфейс Middleware.

Directories

Path Synopsis
middleware

Jump to

Keyboard shortcuts

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