Documentation
¶
Index ¶
- Constants
- Variables
- func AllowAll(allowedOrigins []string) *cors.Cors
- func BearerToken(next http.Handler) http.Handler
- func GetReqID(ctx context.Context) string
- func Logger(next http.Handler) http.Handler
- func NextRequestID() uint64
- func PrintPrettyStack(rvr interface{})
- func PushTelemetry(data et.Json)
- func PushTelemetryLog(data string)
- func PushTelemetryOverflow(data et.Json)
- func PushTokenLastUse(data et.Json)
- func Recoverer(next http.Handler) http.Handler
- func RequestID(next http.Handler) http.Handler
- func RequestLogger(f LogFormatter) func(next http.Handler) http.Handler
- func WithLogEntry(r *http.Request, entry LogEntry) *http.Request
- type DefaultLogFormatter
- type LogEntry
- type LogFormatter
- type LoggerInterface
- type Metrics
- func (m *Metrics) CallLatency()
- func (m *Metrics) CallMetrics() Telemetry
- func (m *Metrics) CallResponseTime()
- func (m *Metrics) CallSearchTime()
- func (m *Metrics) DoneHTTP(rw *ResponseWriterWrapper) et.Json
- func (m *Metrics) DoneRpc(r any) et.Json
- func (m *Metrics) HTTPError(w http.ResponseWriter, r *http.Request, statusCode int, message string) error
- func (m *Metrics) ITEM(w http.ResponseWriter, r *http.Request, statusCode int, dt et.Item) error
- func (m *Metrics) ITEMS(w http.ResponseWriter, r *http.Request, statusCode int, dt et.Items) error
- func (m *Metrics) JSON(w http.ResponseWriter, r *http.Request, statusCode int, dt interface{}) error
- func (m *Metrics) RESULT(w http.ResponseWriter, r *http.Request, statusCode int, data interface{}) error
- func (m *Metrics) SetPath(val string)
- func (m *Metrics) ToJson() et.Json
- func (m *Metrics) WriteResponse(w http.ResponseWriter, r *http.Request, statusCode int, e []byte) error
- type ResponseWriterWrapper
- type Telemetry
- type WrapResponseWriter
Constants ¶
const ( ERR_AUTORIZATION_IS_REQUIRED = "Autorization is required" ERR_INVALID_AUTORIZATION_FORMAT = "Invalid autorization format" )
const ( TELEMETRY = "telemetry" TELEMETRY_LOG = "telemetry:log" TELEMETRY_OVERFLOW = "telemetry:overflow" TELEMETRY_TOKEN_LAST_USE = "telemetry:token:last_use" MetricKey request.ContextKey = "metric" )
const RequestIDKey ctxKeyRequestID = 0
RequestIDKey is the key that holds the unique request ID in a request context.
Variables ¶
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 )
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 BearerToken ¶ added in v1.0.21
* * BearerToken * @param next http.Handler *
func GetReqID ¶
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 ¶
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
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
PushTelemetryOverflow publishes a rate-limit overflow event asynchronously.
func PushTokenLastUse ¶ added in v0.1.16
PushTokenLastUse publishes a token last-use event asynchronously.
func Recoverer ¶
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 ¶
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.
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 ¶
GetLogEntry returns the in-context LogEntry for a request.
type LogFormatter ¶
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
GetMetrics retrieves the Metrics stored in the request context, or creates a new one.
func NewMetric ¶
NewMetric creates a Metrics instance populated from the incoming HTTP request. Client IP resolution order: X-Forwarded-For → X-Real-IP → RemoteAddr.
func NewRpcMetric ¶
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 ¶
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) 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) 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) 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.
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.