Skip to content

About

Compogo HTTP Client — это гибкий и расширяемый HTTP-клиент для Go.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

6 Commits

Folders and files

Repository files navigation

Compogo HTTP Client

Go Reference License: MIT

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.

About

Compogo HTTP Client — это гибкий и расширяемый HTTP-клиент для Go.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

⌂ 换网址