middleware

package
v1.0.21 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2026 License: MIT Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ERR_AUTORIZATION_IS_REQUIRED    = "Autorization is required"
	ERR_INVALID_AUTORIZATION_FORMAT = "Invalid autorization format"
)
View Source
const (
	TELEMETRY                                   = "telemetry"
	TELEMETRY_LOG                               = "telemetry:log"
	TELEMETRY_OVERFLOW                          = "telemetry:overflow"
	TELEMETRY_TOKEN_LAST_USE                    = "telemetry:token:last_use"
	MetricKey                request.ContextKey = "metric"
)
View Source
const RequestIDKey ctxKeyRequestID = 0

RequestIDKey is the key that holds the unique request ID in a request context.

Variables

View Source
var (
	// LogEntryCtxKey is the context.Context key to store the request log entry.
	LogEntryCtxKey = request.ContextKey("LogEntry")

	// DefaultLogger is called by the Logger middleware handler to log each request.
	// Its made a package-level variable so that it can be reconfigured for custom
	// logging configurations.
	DefaultLogger func(next http.Handler) http.Handler
)
View Source
var RequestIDHeader = "X-Request-Id"

RequestIDHeader is the name of the HTTP Header which contains the request id. Exported so that it can be changed by developers

Functions

func AllowAll

func AllowAll(allowedOrigins []string) *cors.Cors

func BearerToken added in v1.0.21

func BearerToken(next http.Handler) http.Handler

* * BearerToken * @param next http.Handler *

func GetReqID

func GetReqID(ctx context.Context) string

GetReqID returns a request ID from the given context if one is present. Returns the empty string if a request ID cannot be found.

func Logger

func Logger(next http.Handler) http.Handler

Logger is a middleware that logs the start and end of each request, along with some useful data about what was requested, what the response status was, and how long it took to return. When standard output is a TTY, Logger will print in color, otherwise it will print in black and white. Logger prints a request ID if one is provided.

Alternatively, look at https://github.com/goware/httplog for a more in-depth http logger with structured logging support.

IMPORTANT NOTE: Logger should go before any other middleware that may change the response, such as `middleware.Recoverer`. Example:

```go r := chi.NewRouter() r.Use(middleware.Logger) // <--<< Logger should come before Recoverer r.Use(middleware.Recoverer) r.Get("/", handler) ```

func NextRequestID

func NextRequestID() uint64

NextRequestID generates the next request ID in the sequence.

func PrintPrettyStack

func PrintPrettyStack(rvr interface{})

func PushTelemetry added in v0.1.16

func PushTelemetry(data et.Json)

PushTelemetry publishes a telemetry event asynchronously.

func PushTelemetryLog added in v0.1.18

func PushTelemetryLog(data string)

PushTelemetryLog publishes a log line as a telemetry event asynchronously.

func PushTelemetryOverflow added in v0.1.16

func PushTelemetryOverflow(data et.Json)

PushTelemetryOverflow publishes a rate-limit overflow event asynchronously.

func PushTokenLastUse added in v0.1.16

func PushTokenLastUse(data et.Json)

PushTokenLastUse publishes a token last-use event asynchronously.

func Recoverer

func Recoverer(next http.Handler) http.Handler

Recoverer is a middleware that recovers from panics, logs the panic (and a backtrace), and returns a HTTP 500 (Internal Server Error) status if possible. Recoverer prints a request ID if one is provided.

Alternatively, look at https://github.com/pressly/lg middleware pkgs.

func RequestID

func RequestID(next http.Handler) http.Handler

RequestID is a middleware that injects a request ID into the context of each request. A request ID is a string of the form "host.example.com/random-0001", where "random" is a base62 random string that uniquely identifies this go process, and where the last number is an atomically incremented request counter.

func RequestLogger

func RequestLogger(f LogFormatter) func(next http.Handler) http.Handler

RequestLogger returns a logger handler using a custom LogFormatter.

func WithLogEntry

func WithLogEntry(r *http.Request, entry LogEntry) *http.Request

WithLogEntry sets the in-context LogEntry for a request.

Types

type DefaultLogFormatter

type DefaultLogFormatter struct {
	Logger  LoggerInterface
	NoColor bool
}

DefaultLogFormatter is a simple logger that implements a LogFormatter.

func (*DefaultLogFormatter) NewLogEntry

func (l *DefaultLogFormatter) NewLogEntry(r *http.Request) LogEntry

NewLogEntry creates a new LogEntry for the request.

type LogEntry

type LogEntry interface {
	Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{})
	Panic(v interface{}, stack []byte)
}

LogEntry records the final log when a request completes. See defaultLogEntry for an example implementation.

func GetLogEntry

func GetLogEntry(r *http.Request) LogEntry

GetLogEntry returns the in-context LogEntry for a request.

type LogFormatter

type LogFormatter interface {
	NewLogEntry(r *http.Request) LogEntry
}

LogFormatter initiates the beginning of a new LogEntry per request. See DefaultLogFormatter for an example implementation.

type LoggerInterface

type LoggerInterface interface {
	Print(v ...interface{})
}

LoggerInterface accepts printing to stdlib logger or compatible logger.

type Metrics

type Metrics struct {
	// timestamp — request start time (RFC3339)
	TimeStamp time.Time `json:"timestamp"`
	// Internal correlation ID propagated via ServiceId header
	ServiceId string `json:"service_id"`
	// client.address — originating client IP (X-Forwarded-For > X-Real-IP > RemoteAddr)
	ClientAddress string `json:"client_address"`
	// url.scheme — "http" or "https"
	Scheme string `json:"scheme"`
	// server.address — hostname of this server
	ServerAddress string `json:"server_address"`
	// http.request.method
	Method string `json:"method"`
	// url.path
	Path string `json:"path"`
	// url.query — raw query string
	Query string `json:"query"`
	// http.response.status_code
	StatusCode int `json:"status_code"`
	// http.request.body.size — bytes received
	RequestSize int `json:"request_size"`
	// http.response.body.size — bytes sent
	ResponseSize int `json:"response_size"`
	// user_agent.original
	UserAgent string `json:"user_agent"`
	// trace_id — from X-Trace-ID or X-Request-ID header
	TraceID string `json:"trace_id"`
	// app_name — client application identifier (AppName header)
	AppName string `json:"app_name"`
	// Search/query phase duration in milliseconds
	SearchTime float64 `json:"search_time_ms"`
	// Handler processing duration in milliseconds
	ResponseTime float64 `json:"response_time_ms"`
	// http.server.request.duration — total request latency in milliseconds
	Latency float64 `json:"latency_ms"`
	// contains filtered or unexported fields
}

Metrics holds observability data for a single HTTP or RPC request. Field names and semantics follow OpenTelemetry semantic conventions for HTTP: https://opentelemetry.io/docs/specs/semconv/http/

func GetMetrics added in v0.1.17

func GetMetrics(r *http.Request) *Metrics

GetMetrics retrieves the Metrics stored in the request context, or creates a new one.

func NewMetric

func NewMetric(r *http.Request) *Metrics

NewMetric creates a Metrics instance populated from the incoming HTTP request. Client IP resolution order: X-Forwarded-For → X-Real-IP → RemoteAddr.

func NewRpcMetric

func NewRpcMetric(method string) *Metrics

NewRpcMetric creates a Metrics instance for a JSON-RPC call.

func (*Metrics) CallLatency

func (m *Metrics) CallLatency()

CallLatency records the total end-to-end latency in milliseconds.

func (*Metrics) CallMetrics

func (m *Metrics) CallMetrics() Telemetry

CallMetrics computes rolling request-rate counters for the current endpoint key.

func (*Metrics) CallResponseTime

func (m *Metrics) CallResponseTime()

CallResponseTime records the handler processing duration in milliseconds.

func (*Metrics) CallSearchTime

func (m *Metrics) CallSearchTime()

CallSearchTime records the duration of the search/query phase in milliseconds.

func (*Metrics) DoneHTTP

func (m *Metrics) DoneHTTP(rw *ResponseWriterWrapper) et.Json

DoneHTTP finalizes metrics after an HTTP response has been written.

func (*Metrics) DoneRpc

func (m *Metrics) DoneRpc(r any) et.Json

DoneRpc finalizes metrics after an RPC call has returned.

func (*Metrics) HTTPError

func (m *Metrics) HTTPError(w http.ResponseWriter, r *http.Request, statusCode int, message string) error

HTTPError writes a JSON error response with the given status code and message.

func (*Metrics) ITEM

func (m *Metrics) ITEM(w http.ResponseWriter, r *http.Request, statusCode int, dt et.Item) error

ITEM serializes an et.Item and writes the response.

func (*Metrics) ITEMS

func (m *Metrics) ITEMS(w http.ResponseWriter, r *http.Request, statusCode int, dt et.Items) error

ITEMS serializes an et.Items and writes the response.

func (*Metrics) JSON

func (m *Metrics) JSON(w http.ResponseWriter, r *http.Request, statusCode int, dt interface{}) error

JSON wraps data in a standard {ok, result} envelope and writes the response.

func (*Metrics) RESULT added in v0.1.17

func (m *Metrics) RESULT(w http.ResponseWriter, r *http.Request, statusCode int, data interface{}) error

RESULT serializes data as JSON and writes the response.

func (*Metrics) SetPath

func (m *Metrics) SetPath(val string)

SetPath updates the matched route path and registers the request key.

func (*Metrics) ToJson

func (m *Metrics) ToJson() et.Json

ToJson returns a JSON-serializable representation of the metrics.

func (*Metrics) WriteResponse

func (m *Metrics) WriteResponse(w http.ResponseWriter, r *http.Request, statusCode int, e []byte) error

WriteResponse writes a raw JSON byte response, records metrics, and returns nil on success.

type ResponseWriterWrapper

type ResponseWriterWrapper struct {
	http.ResponseWriter
	StatusCode int
	Size       int
}

ResponseWriterWrapper wraps http.ResponseWriter to capture status code and response size.

func (*ResponseWriterWrapper) Write

func (rw *ResponseWriterWrapper) Write(b []byte) (int, error)

Write delegates to the underlying writer and accumulates the bytes written.

func (*ResponseWriterWrapper) WriteHeader added in v0.0.3

func (rw *ResponseWriterWrapper) WriteHeader(code int)

WriteHeader intercepts the status code before delegating to the underlying writer.

type Telemetry

type Telemetry struct {
	TimeStamp         string `json:"timestamp"`
	AppName           string `json:"service_name"`
	Key               string `json:"key"`
	RequestsPerSecond int64  `json:"requests_per_second"`
	RequestsPerMinute int64  `json:"requests_per_minute"`
	RequestsPerHour   int64  `json:"requests_per_hour"`
	RequestsPerDay    int64  `json:"requests_per_day"`
	RequestsLimit     int64  `json:"requests_limit"`
}

Telemetry holds rate-based request counters for a specific endpoint key.

func (*Telemetry) ToJson

func (t *Telemetry) ToJson() et.Json

ToJson returns a JSON-serializable representation of the telemetry counters.

type WrapResponseWriter

type WrapResponseWriter interface {
	http.ResponseWriter
	// Status returns the HTTP status of the request, or 0 if one has not
	// yet been sent.
	Status() int
	// BytesWritten returns the total number of bytes sent to the client.
	BytesWritten() int
	// Tee causes the response body to be written to the given io.Writer in
	// addition to proxying the writes through. Only one io.Writer can be
	// tee'd to at once: setting a second one will overwrite the first.
	// Writes will be sent to the proxy before being written to this
	// io.Writer. It is illegal for the tee'd writer to be modified
	// concurrently with writes.
	Tee(io.Writer)
	// Unwrap returns the original proxied target.
	Unwrap() http.ResponseWriter
}

WrapResponseWriter is a proxy around an http.ResponseWriter that allows you to hook into various parts of the response process.

func NewWrapResponseWriter

func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter

NewWrapResponseWriter wraps an http.ResponseWriter, returning a proxy that allows you to hook into various parts of the response process.

Jump to

Keyboard shortcuts

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