endpoint

package
v1.67.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2026 License: MIT Imports: 23 Imported by: 2

README

Package endpoint

Пакет endpoint предоставляет инструменты для создания HTTP-обработчиков с поддержкой middleware, валидации данных, логирования и метрик. Упрощает разработку API, автоматизируя рутинные задачи.

Types

Wrapper

Структура для создания оберток вокруг обработчиков. Объединяет:

  • Параметры функции (контекст, запрос, тело и т.д.).
  • Middleware (логирование, метрики, трейсинг).
  • Валидацию и сериализацию данных.

Methods:

NewWrapper(paramMappers []ParamMapper, bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper, logger log.Logger) Wrapper

Конструктор обертки с указанными параметрами.

(m Wrapper) Endpoint(f any) http.HandlerFunc

Преобразовать функцию-обработчик в HTTP-обработчик.

(m Wrapper) WithMiddlewares(middlewares ...http2.Middleware) Wrapper

Билдер-метод для добавления middleware в обертку.

JsonRequestExtractor

Извлекает JSON из тела запроса и валидирует его с помощью объекта, реализующего интерфейс Validator.

Methods:

(j JsonRequestExtractor) Extract(ctx context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error)

Десериализовать JSON и проверить данные через Validator.

JsonResponseMapper

Сериализует ответ в JSON и добавляет заголовки.

Methods:

(j JsonResponseMapper) Map(ctx context.Context, result any, w http.ResponseWriter) error

Упаковка результата в JSON-ответ.

Caller

Структура Caller предоставляет механизм для вызова функций-обработчиков HTTP-запросов, автоматически преобразуя параметры запроса в аргументы функции. Интегрируется с валидацией, извлечением данных и middleware.

Methods:

NewCaller(f any, bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper, paramMappers map[string]ParamMapper) (*Caller, error)

Создает экземпляр Caller для функции-обработчика.

(h *Caller) Handle(ctx context.Context, w http.ResponseWriter, r *http.Request) error

Вызывает функцию-обработчик, передавая ей аргументы, извлеченные из запроса.

Functions

DefaultWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper

Создает предварительно настроенную обертку (Wrapper) для HTTP-обработчиков с базовыми middleware и параметрами. Упрощает создание эндпоинтов, включая валидацию, логирование, метрики и обработку ошибок "из коробки".

Стандартные Middleware:

  • MaxRequestBodySize – ограничивает размер тела запроса (по умолчанию 64 МБ).
  • RequestId – добавляет в контекст requestId, который берет из заголовка x-request-id. Генерирует новый, если не находит.
  • LogMiddleware – логирует данные запросов и ответов.
  • Metrics – собирает метрики: время выполнения, статус-коды, размеры тел.
  • Tracing – интеграция с трейсингом (OpenTelemetry).
  • ErrorHandler – перехватывает и обрабатывает ошибки. Ошибки типа HttpError возвращают структурированный ответ. Остальные ошибки логируются и возвращаются как 500 Internal Server Error.
  • Recovery – предотвращает падение сервера при панике в обработчике, преобразуя ее в ошибку.

Usage

Default usage flow
package main

import (
	"context"
	"log"

	"github.com/txix-open/isp-kit/http"
	"github.com/txix-open/isp-kit/http/endpoint"
	"github.com/txix-open/isp-kit/http/endpoint/httplog"
	"github.com/txix-open/isp-kit/http/router"
	log2 "github.com/txix-open/isp-kit/log"
	"github.com/txix-open/isp-kit/shutdown"
)

type userRequest struct {
	Name string
}

type userResponse struct {
	Id int
}

func foo(ctx context.Context, req userRequest) (userResponse, error) {
	/* put here some business logic */
	return userResponse{Id: 88}, nil
}

func main() {
	logger, err := log2.New()
	if err != nil {
		log.Fatal(err)
	}

	srv := http.NewServer(logger)

	wrapper := endpoint.DefaultWrapper(logger, httplog.Log(logger, true))
	r := router.New()
	r.POST("/foo", wrapper.Endpoint(foo))

	srv.Upgrade(r)

	shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
		log.Println("shutting down...")
		_ = srv.Shutdown(context.Background())
		log.Println("shutdown completed")
	})

	err = srv.ListenAndServe(":8080")
	if err != nil {
		log.Fatal(err)
	}
}

Documentation

Overview

Package endpoint provides a high-level abstraction for building HTTP endpoints with automatic request/response handling, validation, and middleware support. It uses Go generics to create type-safe endpoint implementations.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ErrorHandler

func ErrorHandler(logger log.Logger) http2.Middleware

ErrorHandler is a middleware that logs errors and writes appropriate HTTP responses. It uses the error's logging level and enriches Sentry events with request details. For HttpError implementations, it writes the error using WriteError; otherwise, it returns a generic internal service error to hide implementation details.

func MaxRequestBodySize

func MaxRequestBodySize(maxBytes int64) http2.Middleware

MaxRequestBodySize limits the size of the request body that can be read. It wraps the request body with http.MaxBytesReader to enforce the limit.

func Metrics

func Metrics(storage *http_metrics.ServerStorage) http2.Middleware

Metrics is a middleware that collects HTTP server metrics for each endpoint. It records request duration, status code counts, and request/response body sizes. If the endpoint is not available in the context, it skips metrics collection.

func New added in v1.61.0

func New[Req any, Res any](fn func(ctx context.Context, req Req) (Res, error)) basic[Req, Res]

New creates a new generic endpoint with request and response types. The returned endpoint automatically handles JSON body extraction and response mapping.

func NewDefaultHttp added in v1.61.0

func NewDefaultHttp(fn func(ctx context.Context, w http.ResponseWriter, r *http.Request) error) defaultHttp

NewDefaultHttp creates an endpoint with direct access to ResponseWriter and Request. This is the most flexible option but bypasses automatic body extraction and mapping.

func NewWithRequest added in v1.61.0

func NewWithRequest(fn func(ctx context.Context, r *http.Request) error) withRequest

NewWithRequest creates an endpoint that receives the raw http.Request. Use this when you need direct access to headers, query parameters, or other request details.

func NewWithoutResponse added in v1.61.0

func NewWithoutResponse[Req any](fn func(ctx context.Context, req Req) error) withoutResponseBody[Req]

NewWithoutResponse creates an endpoint that handles a request without returning a response body. Useful for operations like deletions or fire-and-forget actions.

func Recovery

func Recovery() http2.Middleware

Recovery is a middleware that catches panics and converts them to errors. It ensures the server remains stable even when handler code panics. Safe for concurrent use.

func RequestId

func RequestId() http2.Middleware

RequestId is a middleware that manages request IDs for tracing and logging. It uses the existing request ID from headers if present, or generates a new one. The request ID is added to the context and response headers.

Types

type Caller

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

Caller uses reflection to wrap arbitrary functions as HTTP handlers. It automatically extracts request body, builds parameters from the context, and maps return values to the response.

func NewCaller

func NewCaller(
	f any,
	bodyExtractor RequestBodyExtractor,
	bodyMapper ResponseBodyMapper,
	paramMappers map[string]ParamMapper,
) (*Caller, error)

NewCaller creates a new Caller that wraps the provided function. It analyzes the function signature and configures parameter extraction and result mapping. Returns an error if the provided value is not a function or has invalid parameter types.

func (*Caller) Handle

func (h *Caller) Handle(ctx context.Context, w http.ResponseWriter, r *http.Request) error

Handle invokes the wrapped function with extracted parameters and maps the result. It returns an error if parameter extraction fails or the function returns an error.

type HttpError

type HttpError interface {
	WriteError(w http.ResponseWriter) error
}

HttpError is an interface for errors that can write themselves to an HTTP response. Implementations should handle their own HTTP status codes and response formatting.

type JsonRequestExtractor

type JsonRequestExtractor struct {
	Validator Validator
}

JsonRequestExtractor extracts and validates JSON request bodies. It decodes JSON, validates the result, and returns business errors for invalid input.

func (JsonRequestExtractor) Extract

func (j JsonRequestExtractor) Extract(ctx context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error)

Extract decodes the JSON request body into a reflect.Value of the specified type. It validates the decoded value and returns a business error if validation fails.

func (JsonRequestExtractor) ExtractV2 added in v1.61.0

func (j JsonRequestExtractor) ExtractV2(_ context.Context, reader io.Reader, ptr any) error

ExtractV2 decodes the JSON request body into the provided pointer. It validates the decoded value and returns a business error if validation fails.

type JsonResponseMapper

type JsonResponseMapper struct {
}

JsonResponseMapper maps response objects to JSON format. It sets the Content-Type header to application/json and includes the request ID in response headers.

func (JsonResponseMapper) Map

Map marshals the result to JSON and writes it to the http.ResponseWriter. It skips nil results and includes the request ID in the response headers if available.

type LogMiddleware added in v1.40.0

type LogMiddleware http2.Middleware

LogMiddleware is an alias for http.Middleware used for request/response logging.

type ParamBuilder

type ParamBuilder func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error)

ParamBuilder is a function that builds a parameter value from the request context.

type ParamMapper

type ParamMapper struct {
	// Type is the string representation of the parameter type.
	Type string
	// Builder creates the parameter value from the request context.
	Builder ParamBuilder
}

ParamMapper maps a parameter type to its builder function.

func ContextParam

func ContextParam() ParamMapper

ContextParam creates a ParamMapper that provides context.Context to endpoint functions. This is automatically included in the default wrapper.

func RequestParam

func RequestParam() ParamMapper

RequestParam creates a ParamMapper that provides *http.Request to endpoint functions. This is automatically included in the default wrapper.

func ResponseWriterParam

func ResponseWriterParam() ParamMapper

ResponseWriterParam creates a ParamMapper that provides http.ResponseWriter to endpoint functions. This is automatically included in the default wrapper.

type RequestBodyExtractor

type RequestBodyExtractor interface {
	// Extract extracts the request body into a reflect.Value of the specified type.
	Extract(ctx context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error)
	// ExtractV2 extracts the request body into a pointer directly.
	ExtractV2(ctx context.Context, reader io.Reader, ptr any) error
}

RequestBodyExtractor is responsible for extracting and unmarshaling request bodies. It supports both reflection-based and direct pointer-based extraction.

type ResponseBodyMapper

type ResponseBodyMapper interface {
	// Map marshals the result and writes it to the http.ResponseWriter.
	Map(ctx context.Context, result any, w http.ResponseWriter) error
}

ResponseBodyMapper is responsible for marshaling and writing response bodies.

type Validator

type Validator interface {
	// Validate returns true if valid and a map of field names to error messages.
	Validate(value any) (bool, map[string]string)
}

Validator validates a value and returns whether it's valid along with field-level error details.

type Wrappable added in v1.61.0

type Wrappable interface {
	Wrap(wrapper Wrapper) http2.HandlerFunc
}

Wrappable is an interface for types that can be wrapped into an http.HandlerFunc. Implementations should handle request extraction and response mapping.

type Wrapper

type Wrapper struct {
	ParamMappers  map[string]ParamMapper
	BodyExtractor RequestBodyExtractor
	BodyMapper    ResponseBodyMapper
	Middlewares   []http2.Middleware
	Logger        log.Logger
}

Wrapper is the core component for building HTTP endpoints. It combines parameter mapping, body extraction, response mapping, and middleware support.

func DefaultWrapper

func DefaultWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper

DefaultWrapper creates a pre-configured Wrapper with common middleware and settings. It includes request logging, metrics collection, tracing, error handling, and recovery. The default maximum request body size is 64MB.

func NewWrapper

func NewWrapper(
	paramMappers []ParamMapper,
	bodyExtractor RequestBodyExtractor,
	bodyMapper ResponseBodyMapper,
	logger log.Logger,
) Wrapper

NewWrapper creates a new Wrapper with the specified configuration. Parameter mappers are stored in a map for efficient type lookup.

func (Wrapper) Endpoint

func (m Wrapper) Endpoint(f any) http.HandlerFunc

Endpoint wraps a function as an http.HandlerFunc.

Use EndpointV2 with New, NewWithoutResponse, NewWithRequest, or NewDefaultHttp instead. EndpointV2 avoids reflection overhead by using the Wrappable interface.

func (Wrapper) EndpointV2 added in v1.61.0

func (m Wrapper) EndpointV2(w Wrappable) http.HandlerFunc

EndpointV2 wraps a Wrappable implementation as an http.HandlerFunc. It applies middleware in reverse order (last middleware executes first). This version avoids reflection overhead and is preferred for production use.

func (Wrapper) WithMiddlewares

func (m Wrapper) WithMiddlewares(middlewares ...http2.Middleware) Wrapper

WithMiddlewares returns a new Wrapper with additional middleware appended. The original Wrapper remains unchanged (immutable).

Directories

Path Synopsis
Package buffer provides a ResponseWriter wrapper that buffers request and response bodies.
Package buffer provides a ResponseWriter wrapper that buffers request and response bodies.
Package httplog provides HTTP request/response logging middleware.
Package httplog provides HTTP request/response logging middleware.

Jump to

Keyboard shortcuts

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