axmiddleware

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2024 License: MIT Imports: 5 Imported by: 0

README

axmiddleware

Гибкая и типобезопасная библиотека промежуточного ПО (middleware) для Go-приложений, использующая дженерики для обработки любых типов запросов и ответов.

Возможности

  • 🔒 Типобезопасная обработка цепочки middleware с использованием дженериков
  • 🛠 Паттерн Builder для удобной конфигурации
  • 📝 Встроенная поддержка логирования через zerolog
  • ⚡ Поддержка context.Context
  • 🔄 Возможность прерывания цепочки middleware
  • 🏗 Готовые реализации популярных middleware
  • 💪 Встроенная защита от паник

Установка

go get github.com/axgrid/axmiddleware

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

Пример использования библиотеки:

package main

import (
    "context"
    "github.com/axgrid/axmiddleware"
    "github.com/rs/zerolog/log"
)

// Define request and response types
type Request struct {
    Data string
}

type Response struct {
    Result string
}

func main() {
    // Create processor
    processor := axmiddleware.NewProcessor[Request, Response]().
        WithLogger(log.Logger).
        WithMiddlewares(
            axmiddleware.CatchPanicMiddlewares[Request, Response],
            axmiddleware.LogRequestResponseMiddlewares[Request, Response],
        ).
        WithHandlers(handler).
        Build()

    // Process request
    request := Request{Data: "test"}
    response := Response{}
    
    statusCode, err := processor.Process(context.Background(), request, &response)
    if err != nil {
        log.Error().Err(err).Msg("Processing error")
    }
}

func handler(c *axmiddleware.Context[Request, Response]) {
    req := c.Request()
    c.Response().Result = "Processed: " + req.Data
}

Основные концепции

Context

Тип Context[R, S] предоставляет расширенный контекст для обработки, включающий:

  • Доступ к запросу и ответу
  • Управление значениями контекста
  • Обработку ошибок
  • Управление кодами статуса
  • Возможности логирования
  • Управление цепочкой (прерывание, продолжение)
Цепочка Middleware

Middleware выполняются в порядке добавления. Каждый middleware может:

  • Получать доступ к запросу и ответу
  • Изменять контекст
  • Управлять потоком выполнения
  • Обрабатывать ошибки
  • Устанавливать коды статуса
Встроенные Middleware
  1. Обработка паник
axmiddleware.CatchPanicMiddlewares[R, S]

Перехватывает паники в цепочке middleware и логирует ошибки.

  1. Логирование запросов/ответов
axmiddleware.LogRequestResponseMiddlewares[R, S]

Логирует детали запросов и ответов, включая время выполнения.

Продвинутое использование

Создание собственного Middleware
func CustomMiddleware[R, S any](ctx *axmiddleware.Context[R, S]) {
    // Pre-processing
    ctx.Logger().Info().Msg("Before processing")
    
    ctx.Next() // Continue to next middleware
    
    // Post-processing
    ctx.Logger().Info().Msg("After processing")
}
Обработка ошибок
func ErrorHandlingMiddleware[R, S any](ctx *axmiddleware.Context[R, S]) {
    if condition {
        ctx.AbortWithErrorAndCode(400, errors.New("invalid request"))
        return
    }
    ctx.Next()
}
Работа с контекстом
func ContextMiddleware[R, S any](ctx *axmiddleware.Context[R, S]) {
    ctx.WithValue("key", "value")
    ctx.Next()
    
    // Access value in next middlewares
    value := ctx.MustStringValue("key")
}

Особенности использования

  1. Типобезопасность

    • Все операции с запросами и ответами проверяются на этапе компиляции
    • Исключены ошибки приведения типов во время выполнения
  2. Производительность

    • Минимальные накладные расходы благодаря использованию дженериков
    • Эффективная обработка цепочки middleware
  3. Расширяемость

    • Легко добавлять новые middleware
    • Возможность создания составных middleware
    • Гибкая настройка под различные сценарии использования

Требования

  • Go 1.18 или выше (необходима поддержка дженериков)
  • github.com/rs/zerolog для логирования

Лицензия

MIT

Участие в разработке

Мы приветствуем ваше участие в развитии проекта! Создавайте issue и присылайте pull request'ы.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CatchPanicMiddlewares

func CatchPanicMiddlewares[R, S any](ctx *Context[R, S])

func LogRequestResponseMiddlewares

func LogRequestResponseMiddlewares[R, S any](ctx *Context[R, S])

Types

type Context

type Context[R, S any] struct {
	// contains filtered or unexported fields
}

func (*Context[R, S]) Abort

func (c *Context[R, S]) Abort()

func (*Context[R, S]) AbortWithError

func (c *Context[R, S]) AbortWithError(err error)

func (*Context[R, S]) AbortWithErrorAndCode

func (c *Context[R, S]) AbortWithErrorAndCode(code int, err error)

func (*Context[R, S]) Context

func (c *Context[R, S]) Context() context.Context

func (*Context[R, S]) Error

func (c *Context[R, S]) Error(err error)

func (*Context[R, S]) GetError

func (c *Context[R, S]) GetError() error

func (*Context[R, S]) IsAborted

func (c *Context[R, S]) IsAborted() bool

func (*Context[R, S]) Logger

func (c *Context[R, S]) Logger() *zerolog.Logger

func (*Context[R, S]) MustBoolValue

func (c *Context[R, S]) MustBoolValue(key interface{}) bool

func (*Context[R, S]) MustFloat64Value

func (c *Context[R, S]) MustFloat64Value(key interface{}) float64

func (*Context[R, S]) MustInt64Value

func (c *Context[R, S]) MustInt64Value(key interface{}) int64

func (*Context[R, S]) MustIntValue

func (c *Context[R, S]) MustIntValue(key interface{}) int

func (*Context[R, S]) MustStringValue

func (c *Context[R, S]) MustStringValue(key interface{}) string

func (*Context[R, S]) MustStringValueSlice

func (c *Context[R, S]) MustStringValueSlice(key interface{}) []string

func (*Context[R, S]) MustUint64Value

func (c *Context[R, S]) MustUint64Value(key interface{}) uint64

func (*Context[R, S]) MustValue

func (c *Context[R, S]) MustValue(key interface{}) interface{}

func (*Context[R, S]) Next

func (c *Context[R, S]) Next()

func (*Context[R, Q]) Request

func (c *Context[R, Q]) Request() R

func (*Context[P, S]) Response

func (c *Context[P, S]) Response() S

func (*Context[R, S]) Set added in v1.0.2

func (c *Context[R, S]) Set(key, val interface{}) *Context[R, S]

func (*Context[R, S]) SetResponse added in v1.0.3

func (c *Context[R, S]) SetResponse(response S)

func (*Context[R, S]) StatusCode

func (c *Context[R, S]) StatusCode() int

func (*Context[R, S]) Value

func (c *Context[R, S]) Value(key interface{}) interface{}

func (*Context[R, S]) WithValue

func (c *Context[R, S]) WithValue(key, val interface{}) *Context[R, S]

type ContextProcessorBuilder

type ContextProcessorBuilder[R, S any] struct {
	// contains filtered or unexported fields
}

func NewProcessor

func NewProcessor[R, S any]() *ContextProcessorBuilder[R, S]

func (*ContextProcessorBuilder[R, S]) Build

func (b *ContextProcessorBuilder[R, S]) Build() MiddlewareProcessor[R, S]

func (*ContextProcessorBuilder[R, S]) WithContext

func (b *ContextProcessorBuilder[R, S]) WithContext(ctx context.Context) *ContextProcessorBuilder[R, S]

func (*ContextProcessorBuilder[R, S]) WithHandlers

func (b *ContextProcessorBuilder[R, S]) WithHandlers(handlers ...HandlerFunc[R, S]) *ContextProcessorBuilder[R, S]

func (*ContextProcessorBuilder[R, S]) WithLogger

func (b *ContextProcessorBuilder[R, S]) WithLogger(logger zerolog.Logger) *ContextProcessorBuilder[R, S]

func (*ContextProcessorBuilder[R, S]) WithMiddlewares

func (b *ContextProcessorBuilder[R, S]) WithMiddlewares(middlewares ...HandlerFunc[R, S]) *ContextProcessorBuilder[R, S]

type HandlerFunc

type HandlerFunc[R, S any] func(*Context[R, S])

type HandlersChain

type HandlersChain[R, S any] []HandlerFunc[R, S]

type MiddlewareProcessor

type MiddlewareProcessor[R, S any] interface {
	Process(ctx context.Context, request R, response S) (int, error)
}

Jump to

Keyboard shortcuts

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