server_tracing

package
v1.67.2 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 18 Imported by: 0

README

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

Documentation

Overview

Package server_tracing provides HTTP server middleware for distributed tracing.

Index

Constants

This section is empty.

Variables

View Source
var ReadBytesKey = attribute.Key("http.read_bytes")

ReadBytesKey is the attribute key for the total number of bytes read from the request body.

View Source
var WroteBytesKey = attribute.Key("http.wrote_bytes")

WroteBytesKey is the attribute key for the total number of bytes written to the response.

Functions

This section is empty.

Types

type Config

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
}

Config holds the configuration for the HTTP server tracing middleware.

func NewConfig

func NewConfig() Config

NewConfig creates a new Config with default values.

func (Config) Middleware

func (c Config) Middleware() http2.Middleware

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.

Jump to

Keyboard shortcuts

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