MSP-8974 add download flow, server migration to http

This commit is contained in:
chashintv committed 2026-11-23 12:54:59 +03:00
1 parent aa68f6028a
commit 71498785ea
46 files changed
+5102 -124

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
# Package `http`
Пакет `http` предоставляет инструменты для создания и управления HTTP-сервером с поддержкой middleware, обработки
запросов и гибкой настройки. Интегрируется с системой логирования и обработки ошибок.
## Types
### Server
Структура Server управляет жизненным циклом HTTP-сервера, включая запуск, остановку и динамическое обновление
обработчиков.
**Methods:**
#### `NewServer(logger log.Logger, opts ...ServerOption) *Server`
Конструктор сервера. Дополнительно принимает опции:
- `WithServer(server *http.Server) ServerOption` – использование объекта предварительно настроенного HTTP-сервера из
стандартной библиотеки `net/http`.
#### `(s *Server) Upgrade(handler http.Handler)`
Атомарно заменить текущий обработчик запросов на новый.
#### `(s *Server) ListenAndServe(address string) error`
Запустить сервер на указанном адресе.
#### `(s *Server) Serve(listener net.Listener) error`
Запустить сервер на существующем listener.
#### `(s *Server) Shutdown(ctx context.Context) error`
Остановить сервер, завершив все активные соединения.
## Usage
### Default usage flow
```go
package main
import (
"context"
"log"
"net/http"
http2 "github.com/txix-open/isp-kit/http"
log2 "github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/shutdown"
)
func main() {
logger, err := log2.New()
if err != nil {
log.Fatal(err)
}
srv := http2.NewServer(logger)
mux := http.NewServeMux()
mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("hello world!!"))
})
srv.Upgrade(mux)
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)
}
}
```
+95
View File
@@ -0,0 +1,95 @@
# Package `apierrors`
Пакет `apierrors` предоставляет инструменты для создания и управления структурированными ошибками HTTP-API.
Ошибки включают код, сообщение, детали и уровень логирования, а также автоматически сериализуются в JSON для ответов
клиентам.
## Types
### Error
Структура для представления ошибки API. Реализует интерфейс `error`.
**Methods:**
#### `NewInternalServiceError(err error) Error`
Создает ошибку для внутренних сбоев сервера. Возвращает ошибку с HTTP-статусом 500, бизнесовым кодом 900 и уровнем
логирования error.
#### `NewBusinessError(errorCode int, errorMessage string, err error) Error`
Создает бизнес-ошибку (например, невалидные данные от клиента). Возвращает ошибку с HTTP-статусом 400, указанным
бизнесовым кодом и уровнем логирования warn.
#### `New(httpStatusCode int, errorCode int, errorMessage string, err error) Error`
Создает кастомную ошибку с полным контролем параметров.
#### `(e Error) Error() string`
Получить строковое представление ошибки.
#### `(e Error) WriteError(w http.ResponseWriter) error`
Сериализует ошибку в JSON и записывает в `http.ResponseWriter`.
#### `(e Error) WithDetails(details map[string]any) Error`
Добавить детали информации об ошибке.
#### `(e Error) WithLogLevel(level log.Level) Error`
Изменить уровень логирования ошибки.
#### `(e Error) LogLevel() log.Level`
Получить текущий уровень логирования ошибки
## Usage
### Default usage flow
```go
package main
import (
"context"
"errors"
"github.com/txix-open/isp-kit/http/apierrors"
)
type User struct {
Id string
Name string
}
var (
ErrUserNotFound = errors.New("user not found")
ErrUserNotFoundCode = 700
)
type userService interface {
GetUserById(ctx context.Context, id string) (*User, error)
}
type userController struct {
svc userService
}
func (c userController) GetUser(ctx context.Context, userId string) (*User, error) {
result, err := c.svc.GetUserById(ctx, userId)
switch {
case errors.Is(err, ErrUserNotFound):
/* user isn't found so we have to send back specific error code */
return nil, apierrors.NewBusinessError(ErrUserNotFoundCode, ErrUserNotFound.Error(), err)
case err != nil:
/* got some internal error */
return nil, apierrors.NewInternalServiceError(err)
default:
return result, nil
}
}
```
+93
View File
@@ -0,0 +1,93 @@
// Package apierrors provides HTTP error handling with structured error responses.
// It supports business and internal errors with customizable HTTP status codes,
// error codes, and logging levels.
package apierrors
import (
"fmt"
"net/http"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json"
"github.com/txix-open/isp-kit/log"
)
const (
// ErrCodeInternal is the default error code for internal service errors.
ErrCodeInternal = 900
)
// Error represents a structured HTTP error with an error code, message, and optional details.
// It supports custom HTTP status codes, logging levels, and error chaining.
type Error struct {
ErrorCode int
ErrorMessage string
Details map[string]any `json:",omitempty"`
httpStatusCode int
cause error
level log.Level
}
// NewInternalServiceError creates a new internal service error with HTTP 500 status code.
// It logs at Error level and wraps the provided cause error.
func NewInternalServiceError(err error) Error {
return New(http.StatusInternalServerError, ErrCodeInternal, "internal service error", err).WithLogLevel(log.ErrorLevel)
}
// NewBusinessError creates a new business error with HTTP 400 status code.
// It logs at Warn level and is used for client-side validation or business logic errors.
func NewBusinessError(errorCode int, errorMessage string, err error) Error {
return New(http.StatusBadRequest, errorCode, errorMessage, err).WithLogLevel(log.WarnLevel)
}
// New creates a new Error with the specified HTTP status code, error code, message, and cause.
// The default log level is ErrorLevel.
func New(
httpStatusCode int,
errorCode int,
errorMessage string,
err error,
) Error {
return Error{
ErrorCode: errorCode,
ErrorMessage: errorMessage,
httpStatusCode: httpStatusCode,
cause: err,
level: log.ErrorLevel,
}
}
// Error returns a formatted string representation of the error.
func (e Error) Error() string {
return fmt.Sprintf("errorCode: %d, errorMessage: %s, cause: %v", e.ErrorCode, e.ErrorMessage, e.cause)
}
// WriteError writes the error as a JSON response to the http.ResponseWriter.
// It sets the Content-Type header to application/json and the appropriate HTTP status code.
func (e Error) WriteError(w http.ResponseWriter) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(e.httpStatusCode)
err := json.NewEncoder(w).Encode(e)
if err != nil {
return errors.WithMessage(err, "json encode error")
}
return nil
}
// WithDetails adds additional context details to the error.
func (e Error) WithDetails(details map[string]any) Error {
e.Details = details
return e
}
// WithLogLevel sets the logging level for this error.
func (e Error) WithLogLevel(level log.Level) Error {
e.level = level
return e
}
// LogLevel returns the logging level associated with this error.
func (e Error) LogLevel() log.Level {
return e.level
}
+16
View File
@@ -0,0 +1,16 @@
// Package http provides core HTTP server functionality and types for building REST and SOAP services.
// It includes a server implementation, handler wrapper, and middleware support for request processing.
package http
import (
"context"
"net/http"
)
// HandlerFunc is the signature for HTTP handlers that process requests in a context-aware manner.
// Handlers should return an error to indicate processing failure.
type HandlerFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request) error
// Middleware is a function that wraps a HandlerFunc to add cross-cutting concerns
// such as logging, authentication, or metrics collection.
type Middleware func(next HandlerFunc) HandlerFunc
+257
View File
@@ -0,0 +1,257 @@
# 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`
Вызывает функцию-обработчик, передавая ей аргументы, извлеченные из запроса.
## Middlewares
### `MaxRequestBodySize`
Ограничивает размер тела запроса (по умолчанию 64 МБ).
### `RequestId`
Добавляет в контекст requestId, который берет из заголовка x-request-id. Генерирует новый, если не находит.
### `DecodeRequest`
Декодирует запрос при помощи переданного codec, если заголовок `Content-Encoding` совпадает с типом codec.
### `LogMiddleware`
Логирует данные запросов и ответов.
### `Metrics`
Собирает метрики: время выполнения, статус-коды, размеры тел.
### `Tracing`
Интеграция с трейсингом (OpenTelemetry).
### `EncodeResponse`
Кодирует ответ при помощи переданного codec, если заголовок `Accept-Encoding` содержит строку с типом codec (пример значения заголовка `"zstd, identity"`) и размер ответа больше переданного threshold'а, по умолчанию 128 КБ (параметр в байтах).
### `ErrorHandler`
Перехватывает и обрабатывает ошибки. Ошибки типа `HttpError` возвращают структурированный ответ.
Остальные ошибки логируются и возвращаются как 500 Internal Server Error.
### `Recovery`
Предотвращает падение сервера при панике в обработчике, преобразуя ее в ошибку.
## Functions
#### `DefaultWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper`
Создает предварительно настроенную обертку (`Wrapper`) для HTTP-обработчиков с middleware и параметрами.
Упрощает создание эндпоинтов, включая валидацию, логирование, метрики и обработку ошибок "из коробки".
Список Middleware:
- `MaxRequestBodySize`
- `RequestId`
- `LogMiddleware`
- `Metrics`
- `Tracing`
- `ErrorHandler`
- `Recovery`
#### `DefaultCodecWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper`
Создает предварительно настроенную обертку (`Wrapper`) для HTTP-обработчиков с middleware и параметрами.
Упрощает создание эндпоинтов, включая валидацию, логирование, метрики и обработку ошибок "из коробки".
Список Middleware:
- `MaxRequestBodySize`
- `RequestId`
- `DecodeRequest`
- `LogMiddleware`
- `Metrics`
- `Tracing`
- `EncodeResponse`
- `ErrorHandler`
- `Recovery`
## Usage
### Default usage flow
```go
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)
}
}
```
### Codec usage flow
```go
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.DefaultCodecWrapper(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)
}
}
```
+88
View File
@@ -0,0 +1,88 @@
# Package `buffer`
Пакет `buffer` предоставляет инструменты для буферизации HTTP-запросов и ответов. Используется в middleware для
логирования, метрик и других задач, требующих доступа к телам запросов и ответов без их модификации.
## Types
### Buffer
Структура для перехвата и буферизации данных HTTP-ответа. Реализует интерфейс `http.ResponseWriter`.
**Methods:**
#### `New() *Buffer`
Конструктор буфера. Инициализирует внутренние буферы для тела запроса и ответа.
#### `(m *Buffer) Reset(w http.ResponseWriter)`
Сбрасывает состояние буфера и привязывает его к новому `http.ResponseWriter`.
#### `(m *Buffer) Write(b []byte) (int, error)`
Перехватывает данные, записываемые в ответ, и сохраняет их в буфер.
#### `(m *Buffer) WriteHeader(statusCode int)`
Фиксирует статус-код ответа.
#### `(m *Buffer) ResponseBody() []byte`
Возвращает тело ответа в виде байтов из буфера.
#### `(m *Buffer) RequestBody() []byte`
Возвращает тело запроса в виде байтов из буфера.
#### `(m *Buffer) ReadRequestBody(r io.Reader) error`
Читает тело запроса и сохраняет его в буфер.
#### `(m *Buffer) StatusCode() int`
Возвращает статус-код ответа. Если статус-код не был еще записан, вернется 200 OK.
## Functions
#### `Acquire(w http.ResponseWriter) *Buffer`
Берет буфер из пула и инициализирует его для работы с указанным `http.ResponseWriter`.
#### `Release(w *Buffer)`
Возвращает буфер в пул для повторного использования.
## Usage
### Default usage flow
```go
package main
import (
"log"
"net/http"
"github.com/txix-open/isp-kit/http/endpoint/buffer"
)
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
/* get buffer from pool */
buf := buffer.Acquire(w)
defer buffer.Release(buf)
/* read request body */
_ = buf.ReadRequestBody(r.Body)
r.Body = buffer.NewRequestBody(buf.RequestBody())
next.ServeHTTP(buf, r)
/* log response body */
responseBody := buf.ResponseBody()
log.Printf("Response: %s\n", responseBody)
})
}
```
+88
View File
@@ -0,0 +1,88 @@
// Package buffer provides a ResponseWriter wrapper that buffers request and response bodies.
// It is used for logging and metrics collection in HTTP middleware.
package buffer
import (
"bytes"
"io"
"net/http"
)
const (
// defaultBufferSize is the initial buffer size in bytes.
defaultBufferSize = 1024
)
// Buffer wraps http.ResponseWriter to capture request and response bodies.
// It is commonly used in middleware for logging and metrics collection.
type Buffer struct {
http.ResponseWriter
requestBuffer *bytes.Buffer
responseBuffer *bytes.Buffer
statusCode int
}
// New creates a new Buffer with initialized request and response buffers.
func New() *Buffer {
return &Buffer{
requestBuffer: bytes.NewBuffer(make([]byte, defaultBufferSize)),
responseBuffer: bytes.NewBuffer(make([]byte, defaultBufferSize)),
}
}
// Reset reinitializes the buffer with a new ResponseWriter and clears internal state.
// It should be called before reusing a pooled Buffer.
func (m *Buffer) Reset(w http.ResponseWriter) {
m.ResponseWriter = w
m.statusCode = 0
m.responseBuffer.Reset()
m.requestBuffer.Reset()
}
// Write writes data to both the underlying ResponseWriter and the response buffer.
// It returns the number of bytes written and any error encountered.
func (m *Buffer) Write(b []byte) (int, error) {
n, err := m.ResponseWriter.Write(b)
if err != nil {
return n, err
}
n, err = m.responseBuffer.Write(b)
if err != nil {
return 0, err
}
return n, nil
}
// WriteHeader captures the status code and delegates to the underlying ResponseWriter.
func (m *Buffer) WriteHeader(statusCode int) {
m.statusCode = statusCode
m.ResponseWriter.WriteHeader(statusCode)
}
// ResponseBody returns the captured response body as a byte slice.
func (m *Buffer) ResponseBody() []byte {
return m.responseBuffer.Bytes()
}
// RequestBody returns the captured request body as a byte slice.
func (m *Buffer) RequestBody() []byte {
return m.requestBuffer.Bytes()
}
// ReadRequestBody reads the entire request body into the buffer.
// It returns an error if the read operation fails.
func (m *Buffer) ReadRequestBody(r io.Reader) error {
_, err := io.Copy(m.requestBuffer, r)
return err
}
// StatusCode returns the captured status code, or http.StatusOK if not set.
func (m *Buffer) StatusCode() int {
if m.statusCode == 0 {
return http.StatusOK
}
return m.statusCode
}
+33
View File
@@ -0,0 +1,33 @@
package buffer
import (
"net/http"
"sync"
)
// pool is a global sync.Pool for reusing Buffer instances.
// It reduces memory allocation overhead by pooling Buffer objects.
var pool = sync.Pool{
New: func() any {
return New()
},
}
// Acquire retrieves a Buffer from the pool and initializes it with the given ResponseWriter.
// It is safe for concurrent use and should be paired with Release.
func Acquire(w http.ResponseWriter) *Buffer {
var buffer *Buffer
var ok bool
buffer, ok = pool.Get().(*Buffer)
if !ok {
buffer = New()
}
buffer.Reset(w)
return buffer
}
// Release returns a Buffer to the pool for reuse.
// It should be called after the Buffer is no longer needed.
func Release(w *Buffer) {
pool.Put(w)
}
@@ -0,0 +1,29 @@
package buffer
import (
"bytes"
)
// RequestBody wraps a bytes.Buffer to provide an io.ReadCloser for request body replay.
// It is used when the request body needs to be read multiple times (e.g., for logging).
type RequestBody struct {
body *bytes.Buffer
}
// NewRequestBody creates a new RequestBody from a byte slice.
func NewRequestBody(body []byte) RequestBody {
return RequestBody{
body: bytes.NewBuffer(body),
}
}
// Read reads data from the underlying buffer into p.
// It returns the number of bytes read and any error encountered.
func (r RequestBody) Read(p []byte) (n int, err error) {
return r.body.Read(p)
}
// Close is a no-op to satisfy the io.ReadCloser interface.
func (r RequestBody) Close() error {
return nil
}
+123
View File
@@ -0,0 +1,123 @@
package endpoint
import (
"context"
"net/http"
"reflect"
"github.com/txix-open/isp-kit/errors"
)
// param represents a function parameter that can be built from the request context.
type param struct {
index int
builder ParamBuilder
}
// 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.
type Caller struct {
bodyExtractor RequestBodyExtractor
bodyMapper ResponseBodyMapper
handler reflect.Value
paramsCount int
params []param
reqBodyIndex int
reqBodyType reflect.Type
hasResult bool
hasError bool
errorIndex int
}
// 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 NewCaller(
f any,
bodyExtractor RequestBodyExtractor,
bodyMapper ResponseBodyMapper,
paramMappers map[string]ParamMapper,
) (*Caller, error) {
rt := reflect.TypeOf(f)
if rt.Kind() != reflect.Func {
return nil, errors.New("function expected")
}
paramsCount := rt.NumIn()
reqBodyIndex := -1
handler := reflect.ValueOf(f)
var reqBodyType reflect.Type
params := make([]param, 0, paramsCount)
for i := range paramsCount {
p := rt.In(i)
paramType := p.String()
mapper, ok := paramMappers[paramType]
if !ok { // maybe it's a request body
if reqBodyIndex != -1 {
return nil, errors.Errorf("param mapper not found for type %s", paramType)
}
reqBodyIndex = i
reqBodyType = p
continue
}
// it's a simple param
params = append(params, param{index: i, builder: mapper.Builder})
}
numOut := rt.NumOut()
hasResult := numOut > 0 && rt.Out(0) != reflect.TypeFor[*error]().Elem()
hasError := numOut > 0 && rt.Out(numOut-1) == reflect.TypeFor[*error]().Elem()
return &Caller{
bodyExtractor: bodyExtractor,
bodyMapper: bodyMapper,
handler: handler,
paramsCount: paramsCount,
params: params,
reqBodyIndex: reqBodyIndex,
reqBodyType: reqBodyType,
hasResult: hasResult,
hasError: hasError,
errorIndex: numOut - 1,
}, nil
}
// 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.
func (h *Caller) Handle(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
args := make([]reflect.Value, h.paramsCount)
if h.reqBodyIndex != -1 {
value, err := h.bodyExtractor.Extract(ctx, r.Body, h.reqBodyType)
if err != nil {
return err
}
args[h.reqBodyIndex] = value
}
for _, p := range h.params {
value, err := p.builder(ctx, w, r)
if err != nil {
return err
}
args[p.index] = reflect.ValueOf(value)
}
out := h.handler.Call(args)
if h.hasError && !out[h.errorIndex].IsNil() {
return out[h.errorIndex].Interface().(error) // nolint:forcetypeassert
}
if h.hasResult {
return h.bodyMapper.Map(ctx, out[0].Interface(), w)
}
return nil
}
+201
View File
@@ -0,0 +1,201 @@
package endpoint
import (
"bufio"
"bytes"
"context"
"io"
"net"
"net/http"
"strings"
"github.com/txix-open/isp-kit/codec"
"github.com/txix-open/isp-kit/errors"
http2 "github.com/txix-open/isp-kit/http"
)
type DecodeCodec interface {
Type() string
Decode(r io.ReadCloser) (io.ReadCloser, error)
}
const (
defaultEncodeThreshold = codec.DefaultEncodeThreshold
)
// DecodeRequest returns middleware that transparently handles encoded requests.
//
// If Content-Encoding matches codec, request body is decoded.
//
// Important:
// - Should be placed before logging middleware if logs must see decoded data.
func DecodeRequest(codec DecodeCodec) http2.Middleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
if r.Header.Get("Content-Encoding") == codec.Type() {
decoded, err := codec.Decode(r.Body)
if err != nil {
return err
}
r.Body = decoded
r.Header.Del("Content-Encoding")
r.Header.Del("Content-Length")
}
return next(ctx, w, r)
}
}
}
type EncodeCodec interface {
Type() string
Encode(w io.Writer) (io.WriteCloser, error)
}
// EncodeResponse returns middleware that transparently handles response encoding.
//
// If client supports Accept-Encoding and response body size > encodeThresholdBytes,
// the response is encoded using codec.
//
// The middleware finalizes the response after the handler returns. It may
// implicitly call WriteHeader(http.StatusOK) and flush buffered response data
// even if the handler never calls Write or WriteHeader.
//
// Important:
// - Should be placed before logging middleware if logs must see plain data.
func EncodeResponse(codec EncodeCodec, encodeThresholdBytes int) http2.Middleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
if !acceptsEncoding(r.Header.Get("Accept-Encoding"), codec.Type()) {
return next(ctx, w, r)
}
cw := newEncoderWriter(w, codec, encodeThresholdBytes)
err := next(ctx, cw, r)
closeErr := cw.Close()
if err != nil {
return err
}
return closeErr
}
}
}
type encoderWriter struct {
http.ResponseWriter
codec EncodeCodec
buffer bytes.Buffer
encodeThreshold int
writer io.WriteCloser
status int
}
func newEncoderWriter(w http.ResponseWriter, codec EncodeCodec, encodeThreshold int) *encoderWriter {
return &encoderWriter{
ResponseWriter: w,
codec: codec,
encodeThreshold: encodeThreshold,
}
}
func (w *encoderWriter) WriteHeader(code int) {
if w.status != 0 {
return
}
w.status = code
}
func (w *encoderWriter) Write(b []byte) (int, error) {
if w.writer != nil {
return w.writer.Write(b)
}
// fast path: big first write
if w.buffer.Len() == 0 && len(b) > w.encodeThreshold {
return w.startEncoding(b)
}
n, err := w.buffer.Write(b)
if err != nil {
return n, err
}
if w.buffer.Len() > w.encodeThreshold {
data := append([]byte(nil), w.buffer.Bytes()...)
w.buffer.Reset()
return w.startEncoding(data)
}
return n, nil
}
func (w *encoderWriter) Close() error {
if w.writer != nil {
return w.writer.Close()
}
status := w.status
if status == 0 {
status = http.StatusOK
}
w.ResponseWriter.WriteHeader(status)
_, err := w.ResponseWriter.Write(w.buffer.Bytes())
return err
}
// Hijack implements http.Hijacker.
//
// Hijacking is only allowed before the response has started (no buffered or
// encoded data). Once any response data has been written or encoding has been
// triggered, hijacking is disallowed to prevent losing buffered state and to
// preserve response integrity.
func (w *encoderWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if w.writer != nil || w.buffer.Len() > 0 || w.status != 0 {
return nil, nil, errors.New("encoderWriter: hijack not allowed after response started")
}
upstream, ok := w.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, errors.New("encoderWriter: upstream writer doesn't implement Hijack")
}
return upstream.Hijack()
}
func (w *encoderWriter) startEncoding(b []byte) (int, error) {
writer, err := w.codec.Encode(w.ResponseWriter)
if err != nil {
return 0, err
}
w.writer = writer
h := w.Header()
h.Set("Content-Encoding", w.codec.Type())
h.Add("Vary", "Accept-Encoding")
h.Del("Content-Length")
status := w.status
if status == 0 {
status = http.StatusOK
}
w.ResponseWriter.WriteHeader(status)
return w.writer.Write(b)
}
func acceptsEncoding(header, encoding string) bool {
for part := range strings.SplitSeq(header, ",") {
if strings.TrimSpace(part) == encoding {
return true
}
}
return false
}
+74
View File
@@ -0,0 +1,74 @@
package endpoint
import (
"github.com/txix-open/isp-kit/codec"
"github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/metrics"
"github.com/txix-open/isp-kit/metrics/http_metrics"
"github.com/txix-open/isp-kit/observability/tracing/http/server_tracing"
"github.com/txix-open/isp-kit/validator"
)
// 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 DefaultWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper {
paramMappers := []ParamMapper{
ContextParam(),
ResponseWriterParam(),
RequestParam(),
}
middlewares := append(
[]http.Middleware{
MaxRequestBodySize(defaultMaxRequestBodySize),
RequestId(),
http.Middleware(logMiddleware),
Metrics(http_metrics.NewServerStorage(metrics.DefaultRegistry)),
server_tracing.NewConfig().Middleware(),
ErrorHandler(logger),
Recovery(),
},
restMiddlewares...,
)
return NewWrapper(
paramMappers,
JsonRequestExtractor{Validator: validator.Default},
JsonResponseMapper{},
logger,
).WithMiddlewares(middlewares...)
}
// DefaultCodecWrapper creates a pre-configured Wrapper with common middleware and settings.
// It includes request logging, encode response, decode request, metrics collection, tracing, error handling, and recovery.
// The default maximum request body size is 64MB.
func DefaultCodecWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper {
paramMappers := []ParamMapper{
ContextParam(),
ResponseWriterParam(),
RequestParam(),
}
codec := codec.Default
middlewares := append(
[]http.Middleware{
MaxRequestBodySize(defaultMaxRequestBodySize),
RequestId(),
DecodeRequest(codec),
Metrics(http_metrics.NewServerStorage(metrics.DefaultRegistry)),
server_tracing.NewConfig().Middleware(),
EncodeResponse(codec, defaultEncodeThreshold),
http.Middleware(logMiddleware),
ErrorHandler(logger),
Recovery(),
},
restMiddlewares...,
)
return NewWrapper(
paramMappers,
JsonRequestExtractor{Validator: validator.Default},
JsonResponseMapper{},
logger,
).WithMiddlewares(middlewares...)
}
+89
View File
@@ -0,0 +1,89 @@
# Package `httplog`
Пакет `httplog` предоставляет middleware для логирования HTTP-запросов и ответов. Поддерживает гибкую настройку: выбор
типов контента для логирования тела, управление детализацией и интеграцию с буферизацией данных.
## Functions
#### `Log(logger log.Logger, logBody bool) endpoint.LogMiddleware`
Создает middleware с базовыми настройками:
- Логирует тело запроса/ответа, если `logBody = true`.
- По умолчанию логирует только для `application/json` и `text/xml`.
#### `CombinedLog(logger log.Logger, logBody bool) endpoint.LogMiddleware`
Создает middleware с базовыми настройками:
- Логирует тело запроса/ответа, если `logBody = true`.
- По умолчанию логирует только для `application/json` и `text/xml`.
- Собирает запрос и ответ в 1 лог.
#### `LogWithOptions(logger log.Logger, opts ...Option) endpoint.LogMiddleware`
Создает middleware с кастомными настройками через опции:
- `WithContentTypes(logBodyContentTypes []string) Option` – Задает типы контента, для которых логируется тело (например,
`application/json`).
- `WithLogBody(logBody bool) Option` – Включает/отключает логирование тела запроса и ответа.
- `WithLogResponseBody(logResponseBody bool) Option` – Включает/отключает логирование тела ответа.
- `WithLogRequestBody(logRequestBody bool) Option` – Включает/отключает логирование тела запроса.
- `WithCombinedLog(enable bool) Option` – Включает/отключает сборку запроса/ответа в 1 лог.
## Usage
### Default log middleware
```go
package main
import (
"log"
"github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/http/endpoint/httplog"
log2 "github.com/txix-open/isp-kit/log"
)
func main() {
logger, err := log2.New()
if err != nil {
log.Fatal(err)
}
/* create wrapper with default logging middleware */
wrapper := endpoint.DefaultWrapper(logger, httplog.Log(logger, true))
}
```
### Customize log middleware
```go
package main
import (
"log"
"github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/http/endpoint/httplog"
log2 "github.com/txix-open/isp-kit/log"
)
func main() {
logger, err := log2.New()
if err != nil {
log.Fatal(err)
}
/* create wrapper with custom logging middleware */
wrapper := endpoint.DefaultWrapper(logger, httplog.LogWithOptions(
logger,
httplog.WithLogRequestBody(true), // enable logging request body
httplog.WithLogResponseBody(false), // disable logging response body
httplog.WithContentTypes([]string{"application/custom"}), // only for `application/custom` content-type
))
}
```
@@ -0,0 +1,215 @@
// Package httplog provides HTTP request/response logging middleware.
// It supports separate request and response body logging, combined logging,
// and content-type filtering.
package httplog
import (
"context"
"encoding/base64"
"net/http"
"strconv"
"strings"
"time"
"github.com/txix-open/isp-kit/errors"
http2 "github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/http/endpoint/buffer"
"github.com/txix-open/isp-kit/log"
)
const (
// applicationNameHeader is the HTTP header for base64-encoded application name.
applicationNameHeader = "X-Application-Name"
// applicationIdHeader is the HTTP header for application identity (numeric ID).
applicationIdHeader = "X-Application-Identity"
)
var (
// defaultLogBodyContentTypes specifies the content types for which body logging is enabled.
defaultLogBodyContentTypes = []string{
"application/json",
"text/xml",
}
)
// logConfig holds the configuration for the logging middleware.
type logConfig struct {
logBodyContentTypes []string
logRequestBody bool
logResponseBody bool
combinedLog bool
}
// Log creates a logging middleware that logs requests and responses separately.
// If logBody is true, it logs request and response bodies for supported content types.
func Log(logger log.Logger, logBody bool) endpoint.LogMiddleware {
cfg := &logConfig{
logBodyContentTypes: defaultLogBodyContentTypes,
logRequestBody: logBody,
logResponseBody: logBody,
}
return middleware(logger, cfg)
}
// CombinedLog creates a logging middleware that logs requests and responses in a single entry.
// If logBody is true, it logs request and response bodies for supported content types.
func CombinedLog(logger log.Logger, logBody bool) endpoint.LogMiddleware {
cfg := &logConfig{
logBodyContentTypes: defaultLogBodyContentTypes,
logRequestBody: logBody,
logResponseBody: logBody,
}
return combinedLogMiddleware(logger, cfg)
}
// LogWithOptions creates a logging middleware with custom configuration options.
// By default, body logging is disabled. Use options like WithLogBody, WithCombinedLog
// to customize the behavior.
func LogWithOptions(logger log.Logger, opts ...Option) endpoint.LogMiddleware {
cfg := &logConfig{
logBodyContentTypes: defaultLogBodyContentTypes,
logRequestBody: false,
logResponseBody: false,
combinedLog: false,
}
for _, opt := range opts {
opt(cfg)
}
if cfg.combinedLog {
return combinedLogMiddleware(logger, cfg)
}
return middleware(logger, cfg)
}
// middleware creates a logging middleware that logs requests and responses separately.
func middleware(logger log.Logger, cfg *logConfig) endpoint.LogMiddleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
buf := buffer.Acquire(w)
defer buffer.Release(buf)
now := time.Now()
requestLogFields := []log.Field{
log.String("method", r.Method),
log.String("url", r.URL.String()),
}
requestContentType := r.Header.Get("Content-Type")
if cfg.logRequestBody && matchContentType(requestContentType, cfg.logBodyContentTypes) {
err := buf.ReadRequestBody(r.Body)
if err != nil {
return errors.WithMessage(err, "read request body for logging")
}
err = r.Body.Close()
if err != nil {
return errors.WithMessage(err, "close request reader")
}
r.Body = buffer.NewRequestBody(buf.RequestBody())
requestLogFields = append(requestLogFields, log.ByteString("requestBody", buf.RequestBody()))
}
logger.Debug(ctx, "http handler: request", requestLogFields...)
err := next(ctx, buf, r)
responseLogFields := []log.Field{
log.Int("statusCode", buf.StatusCode()),
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
}
responseContentType := buf.Header().Get("Content-Type")
if cfg.logResponseBody && matchContentType(responseContentType, cfg.logBodyContentTypes) {
responseLogFields = append(responseLogFields, log.ByteString("responseBody", buf.ResponseBody()))
}
logger.Debug(ctx, "http handler: response", responseLogFields...)
return err
}
}
}
// combinedLogMiddleware creates a logging middleware that logs requests and responses in a single entry.
func combinedLogMiddleware(logger log.Logger, cfg *logConfig) endpoint.LogMiddleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
buf := buffer.Acquire(w)
defer buffer.Release(buf)
now := time.Now()
logFields := []log.Field{
log.String("method", r.Method),
log.String("url", r.URL.String()),
}
logFields = append(logFields, applicationLogFields(r)...)
requestContentType := r.Header.Get("Content-Type")
if cfg.logRequestBody && matchContentType(requestContentType, cfg.logBodyContentTypes) {
err := buf.ReadRequestBody(r.Body)
if err != nil {
return errors.WithMessage(err, "read request body for logging")
}
err = r.Body.Close()
if err != nil {
return errors.WithMessage(err, "close request reader")
}
r.Body = buffer.NewRequestBody(buf.RequestBody())
logFields = append(logFields, log.ByteString("requestBody", buf.RequestBody()))
}
err := next(ctx, buf, r)
logFields = append(logFields,
log.Int("statusCode", buf.StatusCode()),
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
)
responseContentType := buf.Header().Get("Content-Type")
if cfg.logResponseBody && matchContentType(responseContentType, cfg.logBodyContentTypes) {
logFields = append(logFields, log.ByteString("responseBody", buf.ResponseBody()))
}
logger.Debug(ctx, "http handler: log", logFields...)
return err
}
}
}
// matchContentType checks if the given content type matches any of the available content types.
// It uses prefix matching to handle content types with parameters (e.g., "application/json; charset=utf-8").
func matchContentType(contentType string, availableContentTypes []string) bool {
for _, content := range availableContentTypes {
if strings.HasPrefix(contentType, content) {
return true
}
}
return false
}
// applicationLogFields extracts application-related log fields from the request.
// It decodes the base64-encoded application name and parses the application ID.
func applicationLogFields(r *http.Request) []log.Field {
logFields := make([]log.Field, 0)
appName := r.Header.Get(applicationNameHeader)
if appName != "" {
decodedName, err := base64.StdEncoding.DecodeString(appName)
if err == nil {
logFields = append(logFields, log.String("applicationName", string(decodedName)))
}
}
appId := r.Header.Get(applicationIdHeader)
if appId == "" {
return logFields
}
intAppId, err := strconv.Atoi(appId)
if err == nil {
logFields = append(logFields, log.Int("applicationId", intAppId))
}
return logFields
}
+19
View File
@@ -0,0 +1,19 @@
package httplog
import (
"context"
"net/http"
http2 "github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/endpoint"
)
// Noop returns a no-operation logging middleware that simply passes through requests.
// It is useful as a placeholder or for testing when logging is not needed.
func Noop() endpoint.LogMiddleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
return next(ctx, w, r)
}
}
}
+42
View File
@@ -0,0 +1,42 @@
package httplog
// Option is a function that configures the logConfig.
type Option func(cfg *logConfig)
// WithContentTypes sets the content types for which request and response bodies will be logged.
// Content types are matched using prefix comparison (e.g., "application/json" matches "application/json; charset=utf-8").
func WithContentTypes(logBodyContentTypes []string) Option {
return func(cfg *logConfig) {
cfg.logBodyContentTypes = logBodyContentTypes
}
}
// WithLogBody is a shortcut to enable both request and response body logging.
func WithLogBody(logBody bool) Option {
return func(cfg *logConfig) {
cfg.logResponseBody = logBody
cfg.logRequestBody = logBody
}
}
// WithLogResponseBody enables or disables response body logging.
func WithLogResponseBody(logResponseBody bool) Option {
return func(cfg *logConfig) {
cfg.logResponseBody = logResponseBody
}
}
// WithLogRequestBody enables or disables request body logging.
func WithLogRequestBody(logRequestBody bool) Option {
return func(cfg *logConfig) {
cfg.logRequestBody = logRequestBody
}
}
// WithCombinedLog enables or disables single combined log entry for request and response.
// When enabled, the middleware logs request and response in a single log entry instead of two separate entries.
func WithCombinedLog(enable bool) Option {
return func(cfg *logConfig) {
cfg.combinedLog = enable
}
}
+90
View File
@@ -0,0 +1,90 @@
package endpoint
import (
"context"
"io"
"net/http"
"reflect"
"unicode"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/http/apierrors"
"github.com/txix-open/isp-kit/json"
)
// Validator validates a value and returns whether it's valid along with field-level error details.
type Validator interface {
// Validate returns true if valid and a map of field names to error messages.
Validate(value any) (bool, map[string]string)
}
// JsonRequestExtractor extracts and validates JSON request bodies.
// It decodes JSON, validates the result, and returns business errors for invalid input.
type JsonRequestExtractor struct {
Validator Validator
}
// 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 (j JsonRequestExtractor) Extract(ctx context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error) {
instance := reflect.New(reqBodyType)
err := j.extract(reader, instance.Interface())
if err != nil {
return reflect.Value{}, err
}
elem := instance.Elem()
err = j.validate(elem.Interface())
if err != nil {
return reflect.Value{}, err
}
return elem, nil
}
// ExtractV2 decodes the JSON request body into the provided pointer.
// It validates the decoded value and returns a business error if validation fails.
func (j JsonRequestExtractor) ExtractV2(_ context.Context, reader io.Reader, ptr any) error {
err := j.extract(reader, ptr)
if err != nil {
return err
}
return j.validate(ptr)
}
// extract decodes JSON from the reader into the target pointer.
// It returns a business error with HTTP 400 status for invalid JSON.
func (j JsonRequestExtractor) extract(reader io.Reader, ptr any) error {
err := json.NewDecoder(reader).Decode(ptr)
if err != nil {
err = errors.WithMessage(err, "unmarshal json request body")
return apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
}
return nil
}
// validate validates the decoded value using the configured validator.
// It returns a business error with validation details if validation fails.
func (j JsonRequestExtractor) validate(v any) error {
ok, details := j.Validator.Validate(v)
if ok {
return nil
}
formattedDetails := formatDetails(details)
return apierrors.NewBusinessError(
http.StatusBadRequest,
"invalid request body",
errors.Errorf("validation errors: %v", formattedDetails),
).WithDetails(formattedDetails)
}
// formatDetails converts validation error details by lowercasing the first letter of each field name.
func formatDetails(details map[string]string) map[string]any {
result := make(map[string]any, len(details))
for k, v := range details {
arr := []rune(k)
arr[0] = unicode.ToLower(arr[0])
result[string(arr)] = v
}
return result
}
+37
View File
@@ -0,0 +1,37 @@
package endpoint
import (
"context"
"net/http"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json"
"github.com/txix-open/isp-kit/requestid"
)
// JsonResponseMapper maps response objects to JSON format.
// It sets the Content-Type header to application/json and includes the request ID in response headers.
type JsonResponseMapper struct {
}
// 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.
func (j JsonResponseMapper) Map(ctx context.Context, result any, w http.ResponseWriter) error {
reqId := requestid.FromContext(ctx)
if reqId != "" {
w.Header().Set(requestid.Header, reqId)
}
if result == nil {
return nil
}
w.Header().Set("Content-Type", "application/json")
err := json.EncodeInto(w, result)
if err != nil {
return errors.WithMessage(err, "marshal json")
}
return nil
}
@@ -0,0 +1,71 @@
package endpoint
import (
"context"
"net/http"
"time"
http2 "github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/endpoint/buffer"
"github.com/txix-open/isp-kit/metrics/http_metrics"
)
// scSource is an interface for retrieving the HTTP status code from a response.
type scSource interface {
StatusCode() int
}
// writerWrapper wraps http.ResponseWriter to capture the status code.
// It defaults to http.StatusOK if WriteHeader is not called.
type writerWrapper struct {
http.ResponseWriter
statusCode int
}
// StatusCode returns the captured status code, or http.StatusOK if not set.
func (w *writerWrapper) StatusCode() int {
if w.statusCode == 0 {
return http.StatusOK
}
return w.statusCode
}
// WriteHeader captures the status code and delegates to the underlying ResponseWriter.
func (w *writerWrapper) WriteHeader(statusCode int) {
w.statusCode = statusCode
w.ResponseWriter.WriteHeader(statusCode)
}
// 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 Metrics(storage *http_metrics.ServerStorage) http2.Middleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
endpoint := http_metrics.ServerEndpoint(r.Context())
if endpoint == "" {
return next(ctx, w, r)
}
var scSrc scSource
buf, isBuffer := w.(*buffer.Buffer)
if isBuffer {
scSrc = buf
} else {
scSrc = &writerWrapper{ResponseWriter: w}
}
start := time.Now()
err := next(ctx, w, r)
storage.ObserveDuration(r.Method, endpoint, time.Since(start))
storage.CountStatusCode(r.Method, endpoint, scSrc.StatusCode())
if isBuffer {
storage.ObserveRequestBodySize(r.Method, endpoint, len(buf.RequestBody()))
storage.ObserveResponseBodySize(r.Method, endpoint, len(buf.ResponseBody()))
}
return err
}
}
}
+124
View File
@@ -0,0 +1,124 @@
package endpoint
import (
"context"
"fmt"
"net/http"
"github.com/getsentry/sentry-go"
http2 "github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/apierrors"
"github.com/txix-open/isp-kit/log/logutil"
sentry2 "github.com/txix-open/isp-kit/observability/sentry"
"github.com/txix-open/isp-kit/panic_recovery"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/requestid"
)
const (
// defaultMaxRequestBodySize is the default maximum allowed request body size (64MB).
defaultMaxRequestBodySize = 64 * 1024 * 1024
)
// LogMiddleware is an alias for http.Middleware used for request/response logging.
type LogMiddleware 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 MaxRequestBodySize(maxBytes int64) http2.Middleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
return next(ctx, w, r)
}
}
}
// 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 Recovery() http2.Middleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) (err error) {
defer panic_recovery.Recover(func(panicErr error) {
err = panicErr
})
return next(ctx, w, r)
}
}
}
// 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 ErrorHandler(logger log.Logger) http2.Middleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
err := next(ctx, w, r)
if err == nil {
return nil
}
logFunc := logutil.LogLevelFuncForError(err, logger)
logContext := sentry2.EnrichEvent(ctx, func(event *sentry.Event) {
event.Request = sentryRequest(r)
})
logFunc(logContext, err)
reqId := requestid.FromContext(ctx)
if reqId != "" {
w.Header().Set(requestid.Header, reqId)
}
var httpErr HttpError
if errors.As(err, &httpErr) {
err = httpErr.WriteError(w)
return err
}
// hide error details to prevent potential security leaks
err = apierrors.NewInternalServiceError(err).WriteError(w)
return err
}
}
}
// 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.
func RequestId() http2.Middleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
requestId := r.Header.Get(requestid.Header)
if requestId == "" {
requestId = requestid.Next()
}
ctx = requestid.ToContext(ctx, requestId)
ctx = log.ToContext(ctx, log.String(requestid.LogKey, requestId))
return next(ctx, w, r)
}
}
}
// sentryRequest creates a Sentry request object from an http.Request.
// It determines the protocol based on TLS or X-Forwarded-Proto header.
func sentryRequest(r *http.Request) *sentry.Request {
protocol := "https"
if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
protocol = "http"
}
url := fmt.Sprintf("%s://%s%s", protocol, r.Host, r.URL.Path)
return &sentry.Request{
URL: url,
Method: r.Method,
QueryString: r.URL.RawQuery,
}
}
+39
View File
@@ -0,0 +1,39 @@
package endpoint
import (
"context"
"net/http"
)
// ContextParam creates a ParamMapper that provides context.Context to endpoint functions.
// This is automatically included in the default wrapper.
func ContextParam() ParamMapper {
return ParamMapper{
Type: "context.Context",
Builder: func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error) {
return ctx, nil
},
}
}
// ResponseWriterParam creates a ParamMapper that provides http.ResponseWriter to endpoint functions.
// This is automatically included in the default wrapper.
func ResponseWriterParam() ParamMapper {
return ParamMapper{
Type: "http.ResponseWriter",
Builder: func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error) {
return w, nil
},
}
}
// RequestParam creates a ParamMapper that provides *http.Request to endpoint functions.
// This is automatically included in the default wrapper.
func RequestParam() ParamMapper {
return ParamMapper{
Type: "*http.Request",
Builder: func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error) {
return r, nil
},
}
}
+123
View File
@@ -0,0 +1,123 @@
package endpoint
import (
"context"
"net/http"
http2 "github.com/txix-open/isp-kit/http"
)
// Wrappable is an interface for types that can be wrapped into an http.HandlerFunc.
// Implementations should handle request extraction and response mapping.
type Wrappable interface {
Wrap(wrapper Wrapper) http2.HandlerFunc
}
// basic is a generic endpoint function type that accepts a request and returns a response.
type basic[Req any, Res any] func(ctx context.Context, req Req) (Res, error)
// New creates a new generic endpoint with request and response types.
// The returned endpoint automatically handles JSON body extraction and response mapping.
func New[Req any, Res any](fn func(ctx context.Context, req Req) (Res, error)) basic[Req, Res] {
return fn
}
// Wrap implements Wrappable for basic endpoints.
// It extracts the request body, calls the endpoint function, and maps the response.
func (fn basic[Req, Res]) Wrap(wrapper Wrapper) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
req, err := extractBody[Req](ctx, wrapper, r)
if err != nil {
return err
}
resp, err := fn(ctx, req)
if err != nil {
return err
}
return wrapper.BodyMapper.Map(ctx, resp, w)
}
}
// withoutResponseBody is an endpoint type that processes a request but returns no response body.
type withoutResponseBody[Req any] func(ctx context.Context, req Req) error
// NewWithoutResponse creates an endpoint that handles a request without returning a response body.
// Useful for operations like deletions or fire-and-forget actions.
func NewWithoutResponse[Req any](fn func(ctx context.Context, req Req) error) withoutResponseBody[Req] {
return fn
}
// Wrap implements Wrappable for endpoints without response body.
func (fn withoutResponseBody[Req]) Wrap(wrapper Wrapper) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
req, err := extractBody[Req](ctx, wrapper, r)
if err != nil {
return err
}
return fn(ctx, req)
}
}
// withRequest is an endpoint type that has direct access to the http.Request.
type withRequest func(ctx context.Context, r *http.Request) error
// 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 NewWithRequest(fn func(ctx context.Context, r *http.Request) error) withRequest {
return fn
}
// Wrap implements Wrappable for withRequest endpoints.
func (fn withRequest) Wrap(wrapper Wrapper) http2.HandlerFunc {
return func(ctx context.Context, _ http.ResponseWriter, r *http.Request) error {
return fn(ctx, r)
}
}
// withRequestAndResponse is an endpoint type that has direct access to http.Request and returns a typed response.
type withRequestAndResponse[Res any] func(ctx context.Context, r *http.Request) (Res, error)
// NewWithRequestAndResponse creates an endpoint with direct access to http.Request and automatic response mapping.
// Useful when you need direct access to request details while still returning a typed response.
func NewWithRequestAndResponse[Res any](fn func(ctx context.Context, r *http.Request) (Res, error)) withRequestAndResponse[Res] {
return fn
}
// Wrap implements Wrappable for withRequestAndResponse endpoints.
func (fn withRequestAndResponse[Res]) Wrap(wrapper Wrapper) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
resp, err := fn(ctx, r)
if err != nil {
return err
}
return wrapper.BodyMapper.Map(ctx, resp, w)
}
}
// defaultHttp is an endpoint type that uses the standard http.HandlerFunc signature.
type defaultHttp http2.HandlerFunc
// 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 NewDefaultHttp(fn func(ctx context.Context, w http.ResponseWriter, r *http.Request) error) defaultHttp {
return fn
}
// Wrap implements Wrappable for defaultHttp endpoints.
func (fn defaultHttp) Wrap(wrapper Wrapper) http2.HandlerFunc {
return http2.HandlerFunc(fn)
}
// extractBody extracts and unmarshals the request body into the target type.
// It uses the wrapper's BodyExtractor to handle the request body.
func extractBody[T any](ctx context.Context, w Wrapper, r *http.Request) (T, error) {
var req T
err := w.BodyExtractor.ExtractV2(ctx, r.Body, &req)
if err != nil {
return *new(T), err
}
return req, nil
}
+133
View File
@@ -0,0 +1,133 @@
// 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.
package endpoint
import (
"context"
"io"
"net/http"
"reflect"
"slices"
http2 "github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/log"
)
// 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 HttpError interface {
WriteError(w http.ResponseWriter) error
}
// RequestBodyExtractor is responsible for extracting and unmarshaling request bodies.
// It supports both reflection-based and direct pointer-based extraction.
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
}
// ResponseBodyMapper is responsible for marshaling and writing response bodies.
type ResponseBodyMapper interface {
// Map marshals the result and writes it to the http.ResponseWriter.
Map(ctx context.Context, result any, w http.ResponseWriter) error
}
// ParamBuilder is a function that builds a parameter value from the request context.
type ParamBuilder func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error)
// ParamMapper maps a parameter type to its builder function.
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
}
// Wrapper is the core component for building HTTP endpoints.
// It combines parameter mapping, body extraction, response mapping, and middleware support.
type Wrapper struct {
ParamMappers map[string]ParamMapper
BodyExtractor RequestBodyExtractor
BodyMapper ResponseBodyMapper
Middlewares []http2.Middleware
Logger log.Logger
}
// NewWrapper creates a new Wrapper with the specified configuration.
// Parameter mappers are stored in a map for efficient type lookup.
func NewWrapper(
paramMappers []ParamMapper,
bodyExtractor RequestBodyExtractor,
bodyMapper ResponseBodyMapper,
logger log.Logger,
) Wrapper {
mappers := make(map[string]ParamMapper)
for _, mapper := range paramMappers {
mappers[mapper.Type] = mapper
}
return Wrapper{
ParamMappers: mappers,
BodyExtractor: bodyExtractor,
BodyMapper: bodyMapper,
Logger: logger,
}
}
// 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 (m Wrapper) Endpoint(f any) http.HandlerFunc {
w, isWrappable := f.(Wrappable)
if isWrappable {
return m.EndpointV2(w)
}
caller, err := NewCaller(f, m.BodyExtractor, m.BodyMapper, m.ParamMappers)
if err != nil {
panic(err)
}
handler := caller.Handle
for i := range slices.Backward(m.Middlewares) {
handler = m.Middlewares[i](handler)
}
return func(w http.ResponseWriter, r *http.Request) {
err := handler(r.Context(), w, r)
if err != nil {
m.Logger.Error(r.Context(), err)
}
}
}
// 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 (m Wrapper) EndpointV2(w Wrappable) http.HandlerFunc {
handler := w.Wrap(m)
for i := range slices.Backward(m.Middlewares) {
handler = m.Middlewares[i](handler)
}
return func(w http.ResponseWriter, r *http.Request) {
err := handler(r.Context(), w, r)
if err != nil {
m.Logger.Error(r.Context(), err)
}
}
}
// WithMiddlewares returns a new Wrapper with additional middleware appended.
// The original Wrapper remains unchanged (immutable).
func (m Wrapper) WithMiddlewares(middlewares ...http2.Middleware) Wrapper {
return Wrapper{
ParamMappers: m.ParamMappers,
BodyExtractor: m.BodyExtractor,
BodyMapper: m.BodyMapper,
Middlewares: append(m.Middlewares, middlewares...),
Logger: m.Logger,
}
}
+70
View File
@@ -0,0 +1,70 @@
# Package `router`
Пакет `router` предоставляет обертку над [`httprouter`](https://github.com/julienschmidt/httprouter) с поддержкой метрик
и удобной регистрацией обработчиков.
Интегрируется с системой мониторинга для отслеживания эндпоинтов.
## Types
### Router
Структура для управления HTTP-маршрутами. Обеспечивает регистрацию обработчиков, сбор метрик и работу с параметрами URL.
**Methods:**
#### `New() *Router`
Конструктор роутера.
#### `(r *Router) GET(path string, handler http.Handler) *Router`
Зарегистрировать обработчик для GET-запросов. Аналогичные методы: `POST()`, `PUT()`, `DELETE()`.
#### `(r *Router) Handler(method string, path string, handler http.Handler) *Router`
Зарегистрировать обработчик для произвольного HTTP-метода.
#### `(r *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)`
Обработать HTTP-запрос.
#### `(r *Router) InternalRouter() *httprouter.Router`
Возвращает внутренний экземпляр `httprouter.Router` для кастомных настроек.
## Functions
#### `ParamsFromRequest(http *http.Request) Params`
Извлечь URL-параметры из запроса.
#### `ParamsFromContext(ctx context.Context) Params`
Извлечь URL-параметры из контекста.
## Usage
### Default usage flow
```go
package main
import (
"log"
"net/http"
"github.com/txix-open/isp-kit/http/router"
)
func main() {
r := router.New()
r.GET("/users/:id", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
params := router.ParamsFromRequest(r)
userId := params.ByName("id") /* get id param */
log.Println(userId)
w.WriteHeader(http.StatusOK)
}))
_ = http.ListenAndServe(":8080", r)
}
```
+93
View File
@@ -0,0 +1,93 @@
// Package router provides HTTP request routing with metrics integration.
// It wraps the julienschmidt/httprouter library and adds automatic endpoint metrics collection.
package router
import (
"context"
"fmt"
"net/http"
"github.com/julienschmidt/httprouter"
"github.com/txix-open/isp-kit/metrics/http_metrics"
)
// Params is an alias for httprouter.Params, representing URL path parameters.
type Params = httprouter.Params
// Router wraps httprouter.Router with automatic metrics collection for each endpoint.
// It supports method-based routing (GET, POST, PUT, DELETE) and fluent API for route configuration.
type Router struct {
router *httprouter.Router
}
// New creates a new Router instance with a fresh httprouter backend.
func New() *Router {
return &Router{
router: httprouter.New(),
}
}
// GET registers an HTTP GET handler for the specified path.
// Returns the Router for fluent chaining.
func (r *Router) GET(path string, handler http.Handler) *Router {
return r.Handler(http.MethodGet, path, handler)
}
// POST registers an HTTP POST handler for the specified path.
// Returns the Router for fluent chaining.
func (r *Router) POST(path string, handler http.Handler) *Router {
return r.Handler(http.MethodPost, path, handler)
}
// PUT registers an HTTP PUT handler for the specified path.
// Returns the Router for fluent chaining.
func (r *Router) PUT(path string, handler http.Handler) *Router {
return r.Handler(http.MethodPut, path, handler)
}
// DELETE registers an HTTP DELETE handler for the specified path.
// Returns the Router for fluent chaining.
func (r *Router) DELETE(path string, handler http.Handler) *Router {
return r.Handler(http.MethodDelete, path, handler)
}
// Handler registers a handler for the specified HTTP method and path.
// It automatically wraps the handler with metrics collection.
// Returns the Router for fluent chaining.
func (r *Router) Handler(method string, path string, handler http.Handler) *Router {
r.router.Handler(method, path, r.withMetricEndpoint(method, path, handler))
return r
}
// ServeHTTP implements the http.Handler interface and delegates to the underlying httprouter.
func (r *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
r.router.ServeHTTP(writer, request)
}
// InternalRouter returns the underlying httprouter instance for advanced configuration.
func (r *Router) InternalRouter() *httprouter.Router {
return r.router
}
// withMetricEndpoint wraps a handler to add endpoint metrics to the request context.
// The endpoint is formatted as "METHOD /path" for metrics identification.
func (r *Router) withMetricEndpoint(method string, path string, handler http.Handler) http.Handler {
endpoint := fmt.Sprintf("%s %s", method, path)
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
ctx := http_metrics.ServerEndpointToContext(request.Context(), endpoint)
request = request.WithContext(ctx)
handler.ServeHTTP(writer, request)
})
}
// ParamsFromRequest extracts URL path parameters from an http.Request.
// It retrieves the parameters from the request context.
func ParamsFromRequest(http *http.Request) Params {
return ParamsFromContext(http.Context())
}
// ParamsFromContext extracts URL path parameters from a context.
// It returns empty params if none are present in the context.
func ParamsFromContext(ctx context.Context) Params {
return httprouter.ParamsFromContext(ctx)
}
+115
View File
@@ -0,0 +1,115 @@
// nolint:mnd
package http
import (
"context"
"net"
"net/http"
"sync/atomic"
"time"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/http/apierrors"
"github.com/txix-open/isp-kit/log"
)
// service is an internal wrapper that delegates to the actual HTTP handler.
// It uses atomic.Value for thread-safe handler replacement.
type service struct {
delegate atomic.Value
}
// ServeHTTP implements the http.Handler interface and delegates to the stored handler.
// It returns an internal service error if the handler is not initialized.
func (s *service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
value, ok := s.delegate.Load().(http.Handler)
if !ok {
_ = apierrors.NewInternalServiceError(errors.New("handler is not initialized")).
WriteError(w)
return
}
value.ServeHTTP(w, r)
}
// ServerOption is a function that configures a Server instance.
type ServerOption func(*Server)
// WithServer allows providing a custom *http.Server for advanced configuration.
func WithServer(server *http.Server) ServerOption {
return func(srv *Server) {
srv.server = server
}
}
// Server wraps an http.Server with additional functionality for handler management.
// It provides graceful shutdown and handler upgrade capabilities.
type Server struct {
server *http.Server
service *service
}
// NewServer creates a new HTTP server with the specified logger and options.
// Default timeouts are set: 3 seconds for ReadHeaderTimeout and 120 seconds for IdleTimeout.
// Server is safe for concurrent use.
func NewServer(logger log.Logger, opts ...ServerOption) *Server {
s := &Server{
server: &http.Server{
ReadHeaderTimeout: 3 * time.Second,
IdleTimeout: 120 * time.Second,
ErrorLog: log.StdLoggerWithLevel(
logger,
log.WarnLevel,
log.String("worker", "http server"),
),
},
service: &service{
delegate: atomic.Value{},
},
}
for _, opts := range opts {
opts(s)
}
s.server.Handler = s.service
return s
}
// Shutdown gracefully shuts down the server without interrupting any active connections.
// It delegates to the underlying http.Server.Shutdown method.
func (s *Server) Shutdown(ctx context.Context) error {
return s.server.Shutdown(ctx)
}
// Upgrade replaces the current HTTP handler with a new one.
// This method is safe for concurrent use.
func (s *Server) Upgrade(handler http.Handler) {
s.service.delegate.Store(handler)
}
// ListenAndServe starts the server on the specified address.
// It creates a TCP listener and delegates to Serve.
func (s *Server) ListenAndServe(address string) error {
var lc net.ListenConfig
listener, err := lc.Listen(context.Background(), "tcp", address)
if err != nil {
return errors.WithMessagef(err, "listen: %s", address)
}
return s.Serve(listener)
}
// Serve accepts incoming connections on the specified listener and handles requests.
// It returns nil when the server is gracefully shut down.
func (s *Server) Serve(listener net.Listener) error {
err := s.server.Serve(listener)
if errors.Is(err, http.ErrServerClosed) {
return nil
}
if err != nil {
return errors.WithMessage(err, "serve http")
}
return nil
}
@@ -0,0 +1,61 @@
# Package `server_tracing`
Пакет `server_tracing` предоставляет middleware для серверной части HTTP-приложения, обеспечивая автоматическое создание span'ов OpenTelemetry для обработки входящих HTTP-запросов.
## Types
### Config
Структура `Config` определяет настройки трассировки для входящих HTTP-запросов.
**Fields:**
#### `Provider tracing.TracerProvider`
Провайдер трассировки (по умолчанию `tracing.DefaultProvider`).
#### `Propagator tracing.Propagator`
Пропагатор контекста (по умолчанию `tracing.DefaultPropagator`).
**Methods:**
#### `NewConfig() Config`
Создаёт конфигурацию с провайдером и пропагатором по умолчанию:
#### `func (c Config) Middleware() http2.Middleware`
Возвращает middleware, который добавляет в контекст обработки запроса OpenTelemetry span с необходимыми атрибутами. При этом:
- Используется `Propagator` для извлечения контекста трассировки из входящего запроса.
- Определяется имя span'а на основе маршрута или метода + пути.
- В span записываются стандартные HTTP-атрибуты, request ID, а также (если используется `buffer.Buffer`) количество прочитанных и записанных байт.
- Ошибки логируются и, если уровень логирования `Error`, также записываются в span через `RecordError`.
## Usage
### Default usage flow
```go
package main
import (
"github.com/txix-open/isp-kit/observability/tracing/http/server_tracing"
"github.com/txix-open/isp-kit/http"
)
func main(){
...
tracingCfg := server_tracing.NewConfig()
mux := http.NewServeMux()
handler := http.WrapHandler(tracingCfg.Middleware())(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
// обработка запроса
return nil
})
mux.Handle("/example", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = handler(r.Context(), w, r)
}))
...
}
```
@@ -0,0 +1,117 @@
// Package server_tracing provides HTTP server middleware for distributed tracing.
package server_tracing
import (
"context"
"fmt"
"net/http"
http2 "github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/endpoint/buffer"
"github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/log/logutil"
"github.com/txix-open/isp-kit/metrics/http_metrics"
"github.com/txix-open/isp-kit/observability/tracing"
"github.com/txix-open/isp-kit/observability/tracing/http/semconvutil"
"github.com/txix-open/isp-kit/requestid"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/propagation"
semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
"go.opentelemetry.io/otel/trace"
)
// ReadBytesKey is the attribute key for the total number of bytes read from the request body.
var ReadBytesKey = attribute.Key("http.read_bytes")
// WroteBytesKey is the attribute key for the total number of bytes written to the response.
var WroteBytesKey = attribute.Key("http.wrote_bytes")
// tracerName identifies the tracer for HTTP server tracing.
const tracerName = "isp-kit/observability/tracing/http"
// Config holds the configuration for the HTTP server tracing middleware.
type Config struct {
// Provider is the tracer provider used to create tracers.
Provider tracing.TracerProvider
// Propagator is the text map propagator for context propagation.
Propagator tracing.Propagator
}
// NewConfig creates a new Config with default values.
func NewConfig() Config {
return Config{
Provider: tracing.DefaultProvider,
Propagator: tracing.DefaultPropagator,
}
}
// Middleware returns an HTTP server middleware that creates spans for incoming requests.
// It extracts trace context from request headers, creates a server span, and sets
// appropriate attributes including status code and request details. If the provider
// is a no-op, it returns a pass-through middleware.
func (c Config) Middleware() http2.Middleware {
if tracing.IsNoop(c.Provider) {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
return next(ctx, w, r)
}
}
}
tracer := c.Provider.Tracer(tracerName)
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
ctx = c.Propagator.Extract(ctx, propagation.HeaderCarrier(r.Header))
attributes := semconvutil.HTTPServerRequest("", r)
attributes = append(attributes, tracing.RequestId.String(requestid.FromContext(ctx)))
opts := []trace.SpanStartOption{
trace.WithSpanKind(trace.SpanKindServer),
}
var spanName string
serverEndpoint := http_metrics.ServerEndpoint(ctx)
if serverEndpoint != "" {
attributes = append(attributes, semconv.HTTPRouteKey.String(serverEndpoint))
spanName = serverEndpoint
} else {
spanName = fmt.Sprintf("%s %s", r.Method, r.URL.Path)
}
ctx, span := tracer.Start(ctx, spanName, opts...)
defer span.End()
var scSource scSource
buff, isBuffer := w.(*buffer.Buffer)
if isBuffer {
scSource = buff
} else {
scSource = &writerWrapper{ResponseWriter: w}
}
err := next(ctx, scSource, r)
if isBuffer {
attributes = append(
attributes,
ReadBytesKey.Int(len(buff.RequestBody())),
WroteBytesKey.Int(len(buff.ResponseBody())),
)
}
attributes = append(
attributes,
semconv.HTTPStatusCode(scSource.StatusCode()),
)
if err != nil {
logLevel := logutil.LogLevelForError(err)
if logLevel == log.ErrorLevel {
span.RecordError(err)
}
}
span.SetStatus(semconvutil.HTTPServerStatus(scSource.StatusCode()))
span.SetAttributes(attributes...)
return err
}
}
}
@@ -0,0 +1,48 @@
package server_tracing
import (
"bufio"
"net"
"net/http"
"github.com/txix-open/isp-kit/errors"
)
// scSource is an interface for HTTP response writers that provide status code access.
type scSource interface {
http.ResponseWriter
// StatusCode returns the HTTP status code.
StatusCode() int
}
// writerWrapper wraps an http.ResponseWriter to capture the status code.
type writerWrapper struct {
http.ResponseWriter
// statusCode holds the captured HTTP status code.
statusCode int
}
// Hijack implements the http.Hijacker interface by delegating to the upstream response writer.
// It returns an error if the upstream does not support hijacking.
func (w *writerWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
upstream, ok := w.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, errors.New("writerWrapper: upstream writer doesn't implement Hijack")
}
return upstream.Hijack()
}
// StatusCode returns the captured HTTP status code, or http.StatusOK if not yet set.
func (w *writerWrapper) StatusCode() int {
if w.statusCode == 0 {
return http.StatusOK
}
return w.statusCode
}
// WriteHeader captures the status code and delegates to the upstream response writer.
func (w *writerWrapper) WriteHeader(statusCode int) {
w.statusCode = statusCode
w.ResponseWriter.WriteHeader(statusCode)
}