router

package
v1.9.14 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2024 License: MIT Imports: 13 Imported by: 0

README

HTTP роутинг.

Компонент построен на пакете https://github.com/go-chi/chi, реализует интерфейс github.com/go-chi/chi/v5/Router, который доступен в контейнере объектов.

Объект конфигурации.
type Config struct {
	UseProfile          bool
	HealthCheckEndpoint string
	MetricsEndpoint     string
	PprofEndpoint       string
}

Описание полей:

Поле Описание Значение по умолчанию
HealthCheckEndpoint Конечная точка для проверки работоспособности приложения, этот параметр может быть передан одним из 3-х методов:
- флаг командной строки --server.http.routes.health_check
- переменная окружения SERVER_HTTP_ROUTES_HEALTH_CHECK
- значение в конфиг файле server.http.routes.health_check
/health-check
MetricsEndpoint Конечная точка для получения метрик, этот параметр может быть передан одним из 3-х методов:
- флаг командной строки --server.http.routes.metrics
- переменная окружения SERVER_HTTP_ROUTES_METRICS
- значение в конфиг файле server.http.routes.metrics
/metrics
PprofEndpoint Конечная точка для доступа к гошному pprof, этот параметр может быть передан одним из 3-х методов:
- флаг командной строки --server.http.routes.pprof
- переменная окружения SERVER_HTTP_ROUTES_PPROF
- значение в конфиг файле server.http.routes.pprof
/debug
UseProfile Если "true", в роутинг будет добавлен путь к гошному pprof из параметра PprofEndpoint, этот параметр может быть передан одним из 3-х методов:
- флаг командной строки --trace.pprof
- переменная окружения TRACE_PPROF
- значение в конфиг файле trace.pprof
false

Компонент предоставляет ряд middleware в подпакете middleware:

  • TotalRequestCount - добавляет метрику по общему кол. запросов;
  • DurationMetric - добавляет метрику по времени выполнения запроса;
  • NewParam - помещает параметр из запроса, в контекст, для дальнейшего использования, более подробно middleware.
Дополнительные компоненты.
Метрики.

Метрики добавляются автоматически при добавлении middleware.

go_http_server_requests_total - общее кол. запросов. Доступные лейблы в метрике:

  • app - имя приложения;
  • endpoint - конечная точка (путь) запроса;
  • code - код ответа на запрос.

go_http_server_duration_seconds - время выполнения запроса. Доступные лейблы в метрике:

  • app - имя приложения;
  • endpoint - конечная точка (путь) запроса.

Documentation

Index

Constants

View Source
const (
	UseProfileFieldName          = "trace.pprof"
	HealthCheckEndpointFieldName = "server.http.routes.health_check"
	MetricsEndpointFieldName     = "server.http.routes.metrics"
	PprofEndpointFieldName       = "server.http.routes.pprof"

	UseProfileDefault          = false
	HealthCheckEndpointDefault = "/health-check"
	MetricsEndpointDefault     = "/metrics"
	PprofEndpointDefault       = "/debug"
)

Variables

View Source
var Component = &app.Component{
	Dependencies: app.Components{
		logger.Component,
		configurator.Component,
		reConfiguration.Component,
	},
	Constructor: app.Constructor(func(container container.Container) error {
		return container.Provides(
			NewConfig,
			NewReConfigurationWithConfigurator,
			func(reConfiguration *ReConfiguration) Router { return reConfiguration },
		)
	}),
	BindFlags: app.BindFlags(func(flagSet *pflag.FlagSet, container container.Container) error {
		return container.Invoke(func(config *Config) {
			flagSet.BoolVar(&config.UseProfile, UseProfileFieldName, UseProfileDefault, "if true, add debug path to routing")
			flagSet.StringVar(&config.HealthCheckEndpoint, HealthCheckEndpointFieldName, HealthCheckEndpointDefault, "path for liveness test endpoint")
			flagSet.StringVar(&config.MetricsEndpoint, MetricsEndpointFieldName, MetricsEndpointDefault, "path for metrics endpoint")
			flagSet.StringVar(&config.PprofEndpoint, PprofEndpointFieldName, PprofEndpointDefault, "path for debug endpoint")
		})
	}),
	Run: app.Run(func(container container.Container) error {
		return container.Invoke(func(
			reConfiguration reConfiguration.ReConfiguration,
			informer logger.Informer,
			router *ReConfiguration,
		) {
			reConfiguration.Registration(router)
			informer.Info("http.server.router: registration in the reConfigurator")
		})
	}),
}

Functions

func New

func New(logger logger.Logger) chi.Router

Types

type ChiWrapper

type ChiWrapper struct {
	// contains filtered or unexported fields
}

func NewChiWrapper

func NewChiWrapper(router chi.Router) *ChiWrapper

func (*ChiWrapper) Connect

func (wrapper *ChiWrapper) Connect(pattern string, h http.HandlerFunc)

func (*ChiWrapper) Delete

func (wrapper *ChiWrapper) Delete(pattern string, h http.HandlerFunc)

func (*ChiWrapper) Get

func (wrapper *ChiWrapper) Get(pattern string, h http.HandlerFunc)

func (*ChiWrapper) Group

func (wrapper *ChiWrapper) Group(fn func(r Router))

func (*ChiWrapper) Handle

func (wrapper *ChiWrapper) Handle(pattern string, h http.Handler)

func (*ChiWrapper) HandleFunc

func (wrapper *ChiWrapper) HandleFunc(pattern string, h http.HandlerFunc)

func (*ChiWrapper) Head

func (wrapper *ChiWrapper) Head(pattern string, h http.HandlerFunc)

func (*ChiWrapper) Method

func (wrapper *ChiWrapper) Method(method, pattern string, h http.Handler)

func (*ChiWrapper) MethodFunc

func (wrapper *ChiWrapper) MethodFunc(method, pattern string, h http.HandlerFunc)

func (*ChiWrapper) MethodNotAllowed

func (wrapper *ChiWrapper) MethodNotAllowed(h http.HandlerFunc)

func (*ChiWrapper) Mount

func (wrapper *ChiWrapper) Mount(pattern string, h http.Handler)

func (*ChiWrapper) NotFound

func (wrapper *ChiWrapper) NotFound(h http.HandlerFunc)

func (*ChiWrapper) Options

func (wrapper *ChiWrapper) Options(pattern string, h http.HandlerFunc)

func (*ChiWrapper) Patch

func (wrapper *ChiWrapper) Patch(pattern string, h http.HandlerFunc)

func (*ChiWrapper) Post

func (wrapper *ChiWrapper) Post(pattern string, h http.HandlerFunc)

func (*ChiWrapper) Put

func (wrapper *ChiWrapper) Put(pattern string, h http.HandlerFunc)

func (*ChiWrapper) Route

func (wrapper *ChiWrapper) Route(pattern string, fn func(r Router))

func (*ChiWrapper) ServeHTTP

func (wrapper *ChiWrapper) ServeHTTP(writer http.ResponseWriter, request *http.Request)

func (*ChiWrapper) Trace

func (wrapper *ChiWrapper) Trace(pattern string, h http.HandlerFunc)

func (*ChiWrapper) Use

func (wrapper *ChiWrapper) Use(middlewares ...Middleware)

type Config

type Config struct {
	UseProfile          bool
	HealthCheckEndpoint string
	MetricsEndpoint     string
	PprofEndpoint       string
}

func Configuration

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

func NewConfig

func NewConfig() *Config

type Middleware

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

type MiddlewareFunc

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

func (MiddlewareFunc) Middleware

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

type ReConfiguration

type ReConfiguration struct {
	// contains filtered or unexported fields
}

func NewReConfiguration

func NewReConfiguration(logger logger.Logger, config *Config) *ReConfiguration

func NewReConfigurationWithConfigurator

func NewReConfigurationWithConfigurator(logger logger.Logger, config *Config, configurator configurator.Configurator) *ReConfiguration

func (*ReConfiguration) Connect

func (reConfiguration *ReConfiguration) Connect(pattern string, h http.HandlerFunc)

func (*ReConfiguration) Delete

func (reConfiguration *ReConfiguration) Delete(pattern string, h http.HandlerFunc)

func (*ReConfiguration) Get

func (reConfiguration *ReConfiguration) Get(pattern string, h http.HandlerFunc)

func (*ReConfiguration) Group

func (reConfiguration *ReConfiguration) Group(fn func(r Router))

func (*ReConfiguration) Handle

func (reConfiguration *ReConfiguration) Handle(pattern string, h http.Handler)

func (*ReConfiguration) HandleFunc

func (reConfiguration *ReConfiguration) HandleFunc(pattern string, h http.HandlerFunc)

func (*ReConfiguration) Head

func (reConfiguration *ReConfiguration) Head(pattern string, h http.HandlerFunc)

func (*ReConfiguration) Method

func (reConfiguration *ReConfiguration) Method(method, pattern string, h http.Handler)

func (*ReConfiguration) MethodFunc

func (reConfiguration *ReConfiguration) MethodFunc(method, pattern string, h http.HandlerFunc)

func (*ReConfiguration) MethodNotAllowed

func (reConfiguration *ReConfiguration) MethodNotAllowed(h http.HandlerFunc)

func (*ReConfiguration) Mount

func (reConfiguration *ReConfiguration) Mount(pattern string, h http.Handler)

func (*ReConfiguration) NotFound

func (reConfiguration *ReConfiguration) NotFound(h http.HandlerFunc)

func (*ReConfiguration) Options

func (reConfiguration *ReConfiguration) Options(pattern string, h http.HandlerFunc)

func (*ReConfiguration) Patch

func (reConfiguration *ReConfiguration) Patch(pattern string, h http.HandlerFunc)

func (*ReConfiguration) Post

func (reConfiguration *ReConfiguration) Post(pattern string, h http.HandlerFunc)

func (*ReConfiguration) Put

func (reConfiguration *ReConfiguration) Put(pattern string, h http.HandlerFunc)

func (*ReConfiguration) ReConfiguration

func (reConfiguration *ReConfiguration) ReConfiguration(configurator configurator.Configurator) error

func (*ReConfiguration) Route

func (reConfiguration *ReConfiguration) Route(pattern string, fn func(r Router))

func (*ReConfiguration) Router

func (reConfiguration *ReConfiguration) Router() Router

func (*ReConfiguration) ServeHTTP

func (reConfiguration *ReConfiguration) ServeHTTP(writer http.ResponseWriter, request *http.Request)

func (*ReConfiguration) Trace

func (reConfiguration *ReConfiguration) Trace(pattern string, h http.HandlerFunc)

func (*ReConfiguration) Use

func (reConfiguration *ReConfiguration) Use(middlewares ...Middleware)

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)
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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