http

package module
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2026 License: MIT Imports: 12 Imported by: 0

README

Compogo HTTP 🌐

Compogo HTTP — минималистичный HTTP-сервер для Compogo, построенный поверх Runner. Сервер не содержит встроенного роутинга — вы подключаете любой роутер, реализующий простой интерфейс Router.

🚀 Установка

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

import (
	"net/http"

	"github.com/Compogo/compogo"
	"github.com/Compogo/runner"
	"github.com/Compogo/http"
	"github.com/go-chi/chi/v5" // любой роутер
)

func main() {
	app := compogo.NewApp("myapp",
		compogo.WithOsSignalCloser(),
		runner.WithRunner(),
		http.WithServer(), // добавляем HTTP-сервер
		compogo.WithComponents(
			routerComponent,
		),
	)

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

// Компонент с роутером
var routerComponent = &component.Component{
	Dependencies: component.Components{http.Component},
	Init: component.StepFunc(func(c container.Container) error {
		return c.Provide(newRouter)
	}),
	PostRun: component.StepFunc(func(c container.Container) error {
		return c.Invoke(func(r chi.Router, s http.Server) {
			// регистрируем маршруты
			r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
				w.Write([]byte("Hello, World!"))
			})

			// подключаем к серверу
			s.SetRouter(r)
		})
	}),
}

func newRouter() chi.Router {
	return chi.NewRouter()
}
✨ Возможности
🎯 Чистый HTTP-сервер без лишнего
  • Только слушает порт и отдаёт трафик в роутер
  • Graceful shutdown с таймаутом
  • Интеграция с Runner'ом
  • Конфигурация через флаги
🔌 Поддержка любых роутеров

Интерфейс Router совместим с:

  • chi
  • gorilla/mux
  • http.ServeMux
  • Любым другим, реализующим те же методы
🧩 Middleware
type LoggerMiddleware struct{}

func (m *LoggerMiddleware) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}

// Использование в роутере
router.Use(&LoggerMiddleware{})
⚙️ Конфигурация
./myapp \
    --server.http.interface=0.0.0.0 \
    --server.http.port=8080 \
    --server.http.timeout.shutdown=30s
Флаг По умолчанию Описание
--server.http.interface 0.0.0.0 Интерфейс для прослушивания
--server.http.port 8080 Порт
--server.http.timeout.shutdown 30s Время на завершение активных запросов

Documentation

Index

Constants

View Source
const (
	InterfaceFieldName       = "server.http.interface"
	PortFieldName            = "server.http.port"
	ShutdownTimeoutFieldName = "server.http.timeout.shutdown"

	InterfaceDefault       = "0.0.0.0"
	PortDefault            = uint16(8080)
	ShutdownTimeoutDefault = 30 * time.Second
)

Variables

View Source
var Component = &component.Component{
	Dependencies: component.Components{
		runner.Component,
	},
	Init: component.StepFunc(func(container container.Container) error {
		return container.Provides(
			NewConfig,
			NewServer,
		)
	}),
	BindFlags: component.BindFlags(func(flagSet flag.FlagSet, container container.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: component.StepFunc(func(container container.Container) error {
		return container.Invoke(Configuration)
	}),
	Execute: component.StepFunc(func(container container.Container) error {
		return container.Invoke(func(r runner.Runner, server Server) error {
			return r.RunTask(runner.NewTask("server.http", server))
		})
	}),
	Stop: component.StepFunc(func(container container.Container) error {
		return container.Invoke(func(server Server) error {
			return server.Close()
		})
	}),
}

Component is a ready-to-use Compogo component that provides an HTTP server. It automatically:

  • Registers Config and Server in the DI container
  • Adds command-line flags for server configuration
  • Configures the server during PreRun phase
  • Starts the server as a runner task during PostRun phase
  • Performs graceful shutdown during Stop phase

Usage:

compogo.WithComponents(
    runner.Component,
    http.Component,
    myRouterComponent,  // must implement http.Router
)

Functions

This section is empty.

Types

type Config

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

func Configuration

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

func NewConfig

func NewConfig() *Config

type Middleware

type Middleware interface {
	// Middleware wraps the next handler and returns a new handler.
	// The returned handler should call next.ServeHTTP() to continue the chain.
	Middleware(next http.Handler) http.Handler
}

Middleware defines the interface for HTTP middleware. Middlewares wrap http.Handler to add cross-cutting concerns such as logging, authentication, metrics, or recovery.

Example:

func LoggerMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Printf("%s %s", r.Method, r.URL.Path)
        next.ServeHTTP(w, r)
    })
}

type MiddlewareFunc

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

MiddlewareFunc is a function adapter that allows ordinary functions to be used as Middleware implementations.

func (MiddlewareFunc) Middleware

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

Middleware implements the Middleware interface by calling the underlying function.

type Router

type Router interface {
	// http.Handler makes Router usable as a standard HTTP handler.
	http.Handler

	// Use adds middleware to the router.
	// Middlewares are applied in the order they are added.
	Use(middlewares ...Middleware)

	// Group creates a new sub-router with inherited middleware.
	// All routes defined inside the function will share the same prefix.
	Group(fn func(r Router))

	// Route creates a new sub-router with the given prefix.
	// Similar to Group but without inheriting parent middleware.
	Route(pattern string, fn func(r Router))

	// Mount attaches another http.Handler at the specified pattern.
	// Useful for mounting sub-applications or third-party handlers.
	Mount(pattern string, h http.Handler)

	// Handle registers a handler for the given pattern with all HTTP methods.
	Handle(pattern string, h http.Handler)

	// HandleFunc registers a handler function for the given pattern with all HTTP methods.
	HandleFunc(pattern string, h http.HandlerFunc)

	// Method registers a handler for the given pattern with a specific HTTP method.
	Method(method, pattern string, h http.Handler)

	// MethodFunc registers a handler function for the given pattern with a specific HTTP method.
	MethodFunc(method, pattern string, h http.HandlerFunc)

	// Connect registers a handler for CONNECT method.
	Connect(pattern string, h http.HandlerFunc)

	// Delete registers a handler for DELETE method.
	Delete(pattern string, h http.HandlerFunc)

	// Get registers a handler for GET method.
	Get(pattern string, h http.HandlerFunc)

	// Head registers a handler for HEAD method.
	Head(pattern string, h http.HandlerFunc)

	// Options registers a handler for OPTIONS method.
	Options(pattern string, h http.HandlerFunc)

	// Patch registers a handler for PATCH method.
	Patch(pattern string, h http.HandlerFunc)

	// Post registers a handler for POST method.
	Post(pattern string, h http.HandlerFunc)

	// Put registers a handler for PUT method.
	Put(pattern string, h http.HandlerFunc)

	// Trace registers a handler for TRACE method.
	Trace(pattern string, h http.HandlerFunc)

	// NotFound sets the handler for routes that don't match any pattern.
	NotFound(h http.HandlerFunc)

	// MethodNotAllowed sets the handler for routes that match the path
	// but not the HTTP method.
	MethodNotAllowed(h http.HandlerFunc)
}

Router defines the interface for HTTP routing. It's designed to be compatible with popular routers like chi, gorilla/mux, or the standard library's ServeMux.

The interface includes:

  • Standard HTTP handler methods (Get, Post, Put, etc.)
  • Middleware support (Use)
  • Route grouping (Group, Route)
  • Subtree mounting (Mount)

type Server

type Server interface {
	// Closer io.Closer provides graceful shutdown functionality.
	// It waits for active requests to complete up to ShutdownTimeout.
	io.Closer

	// Process runner.Process allows the server to be run as a task in the runner.
	// The server will block until the context is canceled or an error occurs.
	runner.Process

	// SetRouter attaches a Router to the server.
	// Must be called before starting the server.
	SetRouter(router Router)
}

Server defines the interface for an HTTP server component. It integrates with runner.Runner for lifecycle management and supports graceful shutdown via io.Closer.

func NewServer

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

NewServer creates a new HTTP server instance with the given configuration. The server is not started until it's passed to runner.Runner. The logger is automatically namespaced with "server.http" for better log filtering.

Directories

Path Synopsis
middleware

Jump to

Keyboard shortcuts

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