chi

package module
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2026 License: MIT Imports: 6 Imported by: 0

README

Compogo Chi 🔀

Compogo Chi — это готовая интеграция chi router с фреймворком Compogo. Предоставляет базовый роутер со стандартными middleware и набор компонентов для подключения аутентификации, метрик, логирования, pprof и health checks.

🚀 Установка

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

import (
    "github.com/Compogo/compogo"
    "github.com/Compogo/runner"
    "github.com/Compogo/http"
    "github.com/Compogo/chi"
    "github.com/Compogo/chi/metric"
    "github.com/Compogo/chi/health_check"
)

func main() {
    app := compogo.NewApp("myapp",
        compogo.WithOsSignalCloser(),
        runner.WithRunner(),
        http.WithServer(),
        chi.Component,                    // базовый chi-роутер
        metric.Component,                  // prometheus метрики на /metrics
        health_check.Component,            // health check на /health-check
        compogo.WithComponents(
            myHandlerComponent,
        ),
    )

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

// Ваш компонент с обработчиками
var myHandlerComponent = &component.Component{
    Dependencies: component.Components{chi.Component},
    Run: component.StepFunc(func(c container.Container) error {
        return c.Invoke(func(r http.Router) {
            r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
                w.Write([]byte("Hello, World!"))
            })
        })
    }),
}
✨ Возможности
🎯 Базовый роутер (chi.Component)

Создаёт chi.Router со стандартными middleware:

  • Recoverer — защита от паник
  • Compress — gzip-сжатие ответов
  • RequestLogger — логирование запросов

Автоматически подключается к HTTP-серверу в Run-фазе.

🔌 Интеграция с param
import "github.com/Compogo/chi/param"

page := param.NewParamInt("page", logger,
    param.WithChiURLParam("page"),  // из /users/{page}
    param.WithDefault(1),
)
🧩 Примеры
Полный набор middleware
app := compogo.NewApp("myapp",
    compogo.WithOsSignalCloser(),
    runner.WithRunner(),
    http.WithServer(),
    chi.Component,
    chi_metric.RequestCountComponent,
    chi_metric.DurationComponent,
    chi_logger.RequestComponent,
    chi_logger.ResponseComponent,
    chi_auth_basic.Component,
    chi_pprof.Component,
    chi_health_check.Component,
    compogo.WithComponents(
        yourComponent,
    ),
)
Группы маршрутов
r.Group(func(r http.Router) {
    r.Use(authMiddleware)
    r.Get("/admin", adminHandler)
    r.Get("/profile", profileHandler)
})

r.Route("/api/v1", func(r http.Router) {
    r.Get("/users", listUsers)
    r.Post("/users", createUser)
})

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Component = &component.Component{
	Dependencies: component.Components{
		http.Component,
	},
	Init: component.StepFunc(func(container container.Container) error {
		return container.Provides(
			func(logger logger.Logger) chi.Router {
				router := chi.NewRouter()

				router.Use(
					middleware.Recoverer,
					middleware.RequestLogger(&middleware.DefaultLogFormatter{Logger: logger, NoColor: true}),
				)

				return router
			},
			func(router chi.Router) http.Router { return NewDecorator(router) },
		)
	}),
	PostExecute: component.StepFunc(func(container container.Container) error {
		return container.Invoke(func(r http.Router, server http.Server) {
			server.SetRouter(r)
		})
	}),
}

Component is a ready-to-use Compogo component that provides a chi router. It automatically:

  • Creates a chi router with standard middleware (recoverer, compress, request logger)
  • Provides the router as both chi.Router and http.Router
  • Attaches the router to the HTTP server during Run phase

Usage:

compogo.WithComponents(
    http.Component,
    chi.Component,
    // ... other components that need the router
)

Functions

This section is empty.

Types

type Decorator

type Decorator struct {
	chi.Router
}

Decorator adapts a chi.Router to implement the http.Router interface. This allows any chi router to be used with Compogo's HTTP server component.

func NewDecorator

func NewDecorator(router chi.Router) *Decorator

NewDecorator creates a new Decorator wrapping the provided chi router.

func (*Decorator) Group

func (d *Decorator) Group(fn func(r http.Router))

Group implements http.Router.Group by creating a sub-router with inherited middleware. The provided function receives a wrapped http.Router that operates on the chi sub-router.

func (*Decorator) Route

func (d *Decorator) Route(pattern string, fn func(r http.Router))

Route implements http.Router.Route by creating a new sub-router with the given prefix. The provided function receives a wrapped http.Router that operates on the chi sub-router.

func (*Decorator) Use

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

Use implements http.Router.Use by converting Compogo middlewares to chi middlewares. It iterates through the provided middlewares and adds them to the underlying chi router.

Directories

Path Synopsis
components
middleware

Jump to

Keyboard shortcuts

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