http_server

package module
v1.0.1-rc1 Latest Latest
Warning

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

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

README

Compogo HTTP Server

Go Reference

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

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

  • HTTP-сервер с graceful shutdown
  • Маршрутизацию с поддержкой групп и middleware
  • Аутентификацию (Basic Auth, Token Auth)
  • Логирование запросов и ответов
  • Метрики Prometheus (количество запросов, длительность)
  • Извлечение и валидацию параметров запроса
  • WebSocket (на базе gorilla/websocket)

Установка

go get github.com/Compogo/http

Быстрый старт

package main

import (
    "net/http"

    "github.com/Compogo/compogo"
	httpServer "github.com/Compogo/http_server"
)

func main() {
    app := compogo.NewApp("myapp",
        // Базовые компоненты
        compogo.WithComponents(&httpServer.Component),
    )

    // Настройка роутера
    app.AddComponents(&compogo.Component{
        Name: "router",
        Init: compogo.StepFunc(func(container compogo.Container) error {
            return container.Invoke(func(server httpServer.Server) error {
                router := // ваша реализация Router (например, chi)
                server.SetRouter(router)
                
                router.Get("/health", func(w http.ResponseWriter, r *http.Request) {
                    w.Write([]byte("ok"))
                })
                
                return nil
            })
        }),
    })

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

Компоненты

HTTP Server

HTTP-сервер с поддержкой graceful shutdown.

// Компонент
compogo.WithComponents(&httpServer.Component)

// Настройка через флаги
// --server.http.interface=0.0.0.0
// --server.http.port=8080
// --server.http.timeout.shutdown=30s
Аутентификация
Basic Auth
import "github.com/Compogo/http_server/middleware/basic"

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

// Настройка через флаги
// --server.http.auth.basic.creds=admin:password,user:123
// --server.http.auth.basic.filepath=/path/to/creds.txt

// Использование в роутере
router.Group(func(r http.Router) {
    r.Use(auth)
    r.Get("/admin", adminHandler)
})
Token Auth
import "github.com/Compogo/http_server/middleware/token"

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

// Настройка через флаги
// --server.http.auth.token.tokens=abc123,def456
// --server.http.auth.token.header=X-Auth-Token
// --server.http.auth.token.filepath=/path/to/tokens.txt
Логирование
import "github.com/Compogo/http_server/middleware/logger"

// Подключение компонентов
app.AddComponents(&logger.RequestComponent)
app.AddComponents(&logger.ResponseComponent)

// Логирует путь и тело запроса/ответа на уровне Debug
Метрики Prometheus
import "github.com/Compogo/http_server/middleware/metric"

// Подключение компонентов
app.AddComponents(&metric.RequestCountComponent)
app.AddComponents(&metric.DurationComponent)

// Метрики:
// compogo_http_server_requests_total{app="myapp", code="200", endpoint="/api/users"}
// compogo_http_server_duration_seconds{app="myapp", endpoint="/api/users"}
Параметры запроса
import "github.com/Compogo/http_server/middleware/param"

// Создание параметра
userId := param.NewParamInt("user_id", logger,
    param.WithUriGetter(),
    param.AddValidator(param.GteValidator(1)),
)

// Использование в роутере
router.Get("/users/:id", userId.Middleware(handler))

// Получение из контекста
userID := r.Context().Value("user_id").(int)
WebSocket
import "github.com/Compogo/http_server/websocket"

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

// Создание обработчика
handler := websocket.NewHandler(config, upgrader, logger, closer)

// Подписка на события
handler.OnClientConnection.Subscribe(func(ctx context.Context, client *websocket.Client) {
    logger.Info("client connected")
})

handler.OnMessage.Subscribe(func(ctx context.Context, event *websocket.Event) {
    // обработка входящего сообщения
})

// Регистрация в роутере
router.Get("/ws", handler.ServeHTTP)

// Отправка всем клиентам
handler.Send(websocket.NewEvent("message", payload))

Router

Пакет определяет интерфейс Router, который может быть реализован любой библиотекой маршрутизации:

type Router interface {
    http.Handler
    Use(middlewares ...Middleware)
    Group(fn func(r Router))
    Route(pattern string, fn func(r Router))
    Mount(pattern string, h http.Handler)
    Handle(pattern string, h http.Handler)
    HandleFunc(pattern string, h http.HandlerFunc)
    Method(method, pattern string, h http.Handler)
    MethodFunc(method, pattern string, h http.HandlerFunc)
    Get(pattern string, h http.HandlerFunc)
    Post(pattern string, h http.HandlerFunc)
    Put(pattern string, h http.HandlerFunc)
    Delete(pattern string, h http.HandlerFunc)
    // ... и другие методы
}

Middleware

Написание своего middleware

type MyMiddleware struct {
    logger compogo.Logger
}

func (m *MyMiddleware) Middleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // before
        m.logger.Info("request started")
        
        next.ServeHTTP(w, r)
        
        // after
        m.logger.Info("request finished")
    })
}

// Использование
router.Use(&MyMiddleware{logger: logger})

Helper

// Отправка ошибки в JSON или plain text
helper.WriteError(w, r, "error message", http.StatusBadRequest)

// Отправка ошибки в JSON
helper.JSONError(w, helper.NewError("error message"), http.StatusBadRequest)

Зависимости

Лицензия

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 (
	// InterfaceFieldName — имя поля для сетевого интерфейса.
	InterfaceFieldName = "server.http.interface"

	// PortFieldName — имя поля для порта.
	PortFieldName = "server.http.port"

	// ShutdownTimeoutFieldName — имя поля для таймаута завершения.
	ShutdownTimeoutFieldName = "server.http.timeout.shutdown"
)

Variables

View Source
var (
	// InterfaceDefault — сетевой интерфейс по умолчанию (все интерфейсы).
	InterfaceDefault = "0.0.0.0"

	// PortDefault — порт по умолчанию.
	PortDefault = uint16(8080)

	// ShutdownTimeoutDefault — таймаут завершения по умолчанию (30 секунд).
	ShutdownTimeoutDefault = 30 * time.Second
)
View Source
var Component = compogo.Component{
	Name: "http.server",
	Dependencies: compogo.Components{
		&runner.Component,
	},
	Init: compogo.StepFunc(func(container compogo.Container) error {
		return container.Provides(
			NewConfig,
			NewServer,
		)
	}),
	BindFlags: compogo.BindFlags(func(flagSet flag.FlagSet, container compogo.Container) error {
		return container.Invoke(func(config *Config) {
			flagSet.StringVar(&config.Interface, InterfaceFieldName, InterfaceDefault, "interface for listening to incoming requests")
			flagSet.Uint16Var(&config.Port, PortFieldName, PortDefault, "port for listening to incoming requests")
			flagSet.DurationVar(
				&config.ShutdownTimeout,
				ShutdownTimeoutFieldName,
				ShutdownTimeoutDefault,
				"timeout during which the HTTP server must be turned off after receiving a shutdown signal",
			)
		})
	}),
	Configuration: compogo.StepFunc(func(container compogo.Container) error {
		return container.Invoke(Configuration)
	}),
	PreWait: compogo.StepFunc(func(container compogo.Container) error {
		return container.Invoke(func(r runner.Runner, server Server) error {
			return r.RunProcess(server)
		})
	}),
}

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

Functions

This section is empty.

Types

type Config

type Config struct {
	Interface       string
	Port            uint16
	ShutdownTimeout time.Duration
}

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

func Configuration

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

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

func NewConfig

func NewConfig() *Config

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

type Middleware

type Middleware interface {
	// Middleware оборачивает http.Handler в цепочку обработки.
	Middleware(next http.Handler) http.Handler
}

Middleware представляет функцию-обёртку для HTTP-обработчиков. Позволяет добавлять логирование, авторизацию, метрики и т.д.

type MiddlewareFunc

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

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

Пример:

middleware := MiddlewareFunc(func(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // before
        next.ServeHTTP(w, r)
        // after
    })
})

func (MiddlewareFunc) Middleware

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

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

type Router

type Router interface {
	http.Handler
	Use(middlewares ...Middleware)
	Group(fn func(r Router))
	Route(pattern string, fn func(r Router))
	Mount(pattern string, h http.Handler)
	Handle(pattern string, h http.Handler)
	HandleFunc(pattern string, h http.HandlerFunc)
	Method(method, pattern string, h http.Handler)
	MethodFunc(method, pattern string, h http.HandlerFunc)
	Connect(pattern string, h http.HandlerFunc)
	Delete(pattern string, h http.HandlerFunc)
	Get(pattern string, h http.HandlerFunc)
	Head(pattern string, h http.HandlerFunc)
	Options(pattern string, h http.HandlerFunc)
	Patch(pattern string, h http.HandlerFunc)
	Post(pattern string, h http.HandlerFunc)
	Put(pattern string, h http.HandlerFunc)
	Trace(pattern string, h http.HandlerFunc)
	NotFound(h http.HandlerFunc)
	MethodNotAllowed(h http.HandlerFunc)
}

Router определяет интерфейс HTTP-роутера с поддержкой:

  • Группировки маршрутов
  • Middleware
  • Стандартных HTTP-методов (GET, POST, PUT, DELETE, и т.д.)
  • Вложенных роутеров (Mount)

Интерфейс абстрагирует конкретную реализацию роутера (например, chi, gorilla/mux).

type Server

type Server interface {
	runner.Process
	SetRouter(router Router)
}

Server представляет HTTP-сервер с поддержкой graceful shutdown. Реализует интерфейс runner.Process для интеграции с Runner'ом.

func NewServer

func NewServer(config *Config, logger compogo.Logger) Server

NewServer создаёт новый HTTP-сервер. Принимает конфигурацию и логгер.

Пример:

server := NewServer(config, logger)
server.SetRouter(router)

Directories

Path Synopsis
middleware

Jump to

Keyboard shortcuts

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