requestid

package
v0.0.26 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 8 Imported by: 1

README

Request ID Middleware

What it does

Creates or validates a per-request identifier and exposes it through context/headers for logs, traces, responses, and downstream calls.

How to implement

package main

import (
	"github.com/oarkflow/fh"
	"github.com/oarkflow/fh/mw/requestid"
)

func main() {
	app := fh.New()
	app.Use(requestid.New(requestid.Config{}))

	app.Get("/", func(c fh.Ctx) error {
		return c.Status(fh.StatusOK).SendString("ok")
	})
}

Impact

Very low overhead. Essential for production debugging.

Ordering guidance

Run first or near first before logging, tracing, audit, metrics, and handlers.

Production considerations

Validate incoming IDs to prevent log injection. Use high-entropy IDs when generating new IDs.

Documentation

Index

Constants

View Source
const (
	DefaultHeader   = "X-Request-ID"
	DefaultLocalKey = "request_id"
)

Variables

View Source
var ErrInvalidRequestID = errors.New("requestid: invalid request id")

Functions

func DefaultValidator

func DefaultValidator(id string) bool

func New

func New(config ...Config) fh.HandlerFunc

Types

type AtomicGenerator

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

AtomicGenerator is compact, deterministic, sortable-ish and safe for high throughput. Format:

<node-prefix>-<unixnano-base36>-<counter-base36>

func NewAtomicGenerator

func NewAtomicGenerator() *AtomicGenerator

func NewAtomicGeneratorWithPrefix

func NewAtomicGeneratorWithPrefix(prefix string) *AtomicGenerator

func (*AtomicGenerator) Generate

func (g *AtomicGenerator) Generate(ctx fh.Ctx) string

type Config

type Config struct {
	Header   string
	LocalKey string

	// TrustIncoming controls whether an incoming request ID is accepted.
	TrustIncoming bool

	// MaxIncomingLength prevents oversized or malicious request IDs.
	MaxIncomingLength int

	Generator Generator
	Validator Validator

	ErrorHandler ErrorHandler
}

type ErrorHandler

type ErrorHandler func(ctx fh.Ctx, err error) error

type Generator

type Generator interface {
	Generate(ctx fh.Ctx) string
}

type Validator

type Validator func(id string) bool

Jump to

Keyboard shortcuts

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