requestid

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: 3 Imported by: 3

README

Package requestid

Пакет requestid предоставляет утилиты для генерации и хранения уникального идентификатора запроса (request-id) в контексте.

Constants

Header

Константа Header содержит строку "x-request-id", которая представляет собой стандартное имя HTTP-заголовка, используемого для передачи идентификатора запроса.

LogKey

Константа LogKey содержит строку "requestId" — ключ, под которым request-id может сохраняться в логах.

Types

Данный пакет не экспортирует пользовательских типов.

Functions

ToContext(ctx context.Context, value string) context.Context

Сохраняет request-id в переданном контексте и возвращает новый контекст с сохранённым значением.

FromContext(ctx context.Context) string

Извлекает request-id из контекста. Если значение отсутствует, возвращается пустая строка.

Next() string

Генерирует новый случайный request-id длиной 16 байт (в hex-представлении — 32 символа). Использует криптографически безопасный генератор случайных чисел. В случае ошибки вызывает panic.

Usage

import (
	"net/http"
	"github.com/txix-open/isp-kit/requestid"
)

func handler(w http.ResponseWriter, r *http.Request) {
	id := r.Header.Get(requestid.Header)
	if id == "" {
		id = requestid.Next()
	}
	r = r.WithContext(requestid.ToContext(r.Context(), id))
	// теперь можно использовать FromContext(r.Context()) в любом месте
}

Documentation

Overview

Package requestid provides utilities for managing request IDs in Go applications. It supports storing and retrieving request IDs from context, along with constants for common usage patterns like HTTP headers and log keys.

Index

Constants

View Source
const (
	// Header is the standard HTTP header key for request IDs.
	Header = "x-request-id"
	// LogKey is the key used for request IDs in structured logging.
	LogKey = "requestId"
)

Variables

This section is empty.

Functions

func FromContext

func FromContext(ctx context.Context) string

FromContext extracts the request ID from the context. Returns an empty string if no request ID is set in the context.

func Next

func Next() string

Next generates a new cryptographically secure random request ID. The returned ID is a 32-character hexadecimal string. Panics if a secure random value cannot be generated.

func ToContext

func ToContext(ctx context.Context, value string) context.Context

ToContext stores the request ID in the context and returns the derived context. The request ID can be retrieved later using FromContext.

Types

This section is empty.

Jump to

Keyboard shortcuts

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