middleware

package module
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2025 License: MIT Imports: 16 Imported by: 2

README

zenrpc-middleware: Middlewares for vmkteam/zenrpc

Linter Status Go Report Card Go Reference

zenrpc-middleware is a set of common middlewares for zenrpc implementing logging, metrics and error tracking.

Middlewares

WithDevel

Sets bool flag to context for detecting development environment.

WithHeaders

Sets User-Agent, Platform, Version, X-Country headers to context. User-Agent strips to 2048 chars, Platform and Version – to 64, X-Country - to 16.

WithAPILogger

Logs via Printf function (e.g. log.Printf) all requests. For example

ip= platform="" version="" method=nodevel.arith.divide duration=63.659µs params="{ \"a\": 1, \"b\": 24 }" err=<nil> userAgent="Go-http-client/1.1"
WithSLog

Logs via slog.InfoContext (or similar) function all requests with custom attrs support.

WithSentry

Sets additional parameters for current Sentry scope. Extras: params, duration, ip. Tags: platform, version, method.

WithNoCancelContext

Ignores Cancel func from context. This is useful for passing context to go-pg.

WithMetrics

Logs duration of RPC requests via Prometheus. Default serverName is rpc (will be in server label). It exposes two metrics: app_rpc_error_requests_total and app_rpc_responses_duration_seconds. Labels: method, code, platform, version, server.

WithTiming

Adds timings in JSON-RPC 2.0 Response via extensions field (not in spec). Middleware is active when isDevel=true or AllowDebugFunc returns true. Sample AllowDebugFunc (checks GET/POST parameters for "true" value, like ?d=true):

allowDebugFn := func (param string) middleware.AllowDebugFunc {
    return func (req *http.Request) bool {
        return req.FormValue(param) == "true"
    }
}

DurationLocal – total method execution time in ms.

If DurationRemote or DurationDiff are set then DurationLocal excludes these values.

WithSQLLogger

Adds SQL or DurationSQL fields in JSON-RPC 2.0 Response extensions field (not in spec).

DurationSQL field is set then isDevel=true or AllowDebugFunc(allowDebugFunc) returns true.

SQL field is set then isDevel=true or AllowDebugFunc(allowDebugFunc, allowSqlDebugFunc) returns true.

WithErrorLogger

Logs all errors (ErrorCode==500 or < 0) via Printf func and sends them to Sentry. It also removes sensitive error data from response. It is good to use pkg/errors for stack trace support in sentry.

WithErrorSLog

Same as WithErrorLogger, but for slog.

Examples

Basic usage
package main

import (
	"log"
	"net/http"
	"os"

	"github.com/go-pg/pg/v10"
	"github.com/vmkteam/zenrpc-middleware"
	"github.com/vmkteam/zenrpc/v2"
)

func main() {
	dbс := pg.Connect(&pg.Options{User: "postgres"})
	defer dbс.Close()

	isDevel := true
	elog := log.New(os.Stderr, "E", log.LstdFlags|log.Lshortfile)
	dlog := log.New(os.Stdout, "D", log.LstdFlags|log.Lshortfile)

	allowDebug := func(param string) middleware.AllowDebugFunc {
		return func(req *http.Request) bool {
			return req.FormValue(param) == "true"
		}
	}

	rpc := zenrpc.NewServer(zenrpc.Options{
		ExposeSMD: true,
		AllowCORS: true,
	})

	rpc.Use(
		middleware.WithDevel(isDevel),
		middleware.WithHeaders(),
		middleware.WithAPILogger(dlog.Printf, middleware.DefaultServerName),
		middleware.WithSentry(middleware.DefaultServerName),
		middleware.WithNoCancelContext(),
		middleware.WithMetrics(middleware.DefaultServerName),
		middleware.WithTiming(isDevel, allowDebug("d")),
		middleware.WithSQLLogger(dbc, isDevel, allowDebug("d"), allowDebug("s")),
		middleware.WithErrorLogger(elog.Printf, middleware.DefaultServerName),
	)
}


    // rpc.Register and server

Documentation

Index

Constants

View Source
const (
	// DefaultServerName is a global default name, mostly used for metrics.
	DefaultServerName = ""
)

Variables

View Source
var ErrSkipLog = errors.New("skip log")

ErrSkipLog is a special error for LogAttrs func. Log lines can be skipped.

Functions

func CountryFromContext added in v1.1.6

func CountryFromContext(ctx context.Context) string

CountryFromContext returns country from context. Deprecated: use appkit.CountryFromContext.

func DebugIDFromContext added in v1.1.1

func DebugIDFromContext(ctx context.Context) uint64

DebugIDFromContext returns debug id from context. Deprecated: use appkit.DebugIDFromContext.

func IPFromContext

func IPFromContext(ctx context.Context) string

IPFromContext returns IP from context. Deprecated: use appkit.IPFromContext.

func IsDevelFromContext

func IsDevelFromContext(ctx context.Context) bool

IsDevelFromContext returns isDevel flag from context. Deprecated: use appkit.IsDevelFromContext.

func MethodFromContext added in v1.2.0

func MethodFromContext(ctx context.Context) string

MethodFromContext returns Method from context. Deprecated: use appkit.MethodFromContext.

func NewCountryContext added in v1.1.6

func NewCountryContext(ctx context.Context, country string) context.Context

NewCountryContext creates new context with country. Deprecated: use appkit.NewCountryContext.

func NewDebugIDContext added in v1.1.1

func NewDebugIDContext(ctx context.Context, debugID uint64) context.Context

NewDebugIDContext creates new context with debug ID. Deprecated: use appkit.NewDebugIDContext.

func NewIPContext

func NewIPContext(ctx context.Context, ip string) context.Context

NewIPContext creates new context with IP. Deprecated: use appkit.NewIPContext.

func NewIsDevelContext added in v1.1.1

func NewIsDevelContext(ctx context.Context, isDevel bool) context.Context

NewIsDevelContext creates new context with isDevel flag. Deprecated: use appkit.NewIsDevelContext.

func NewMethodContext added in v1.2.0

func NewMethodContext(ctx context.Context, method string) context.Context

NewMethodContext creates new context with Method. Deprecated: use appkit.NewMethodContext.

func NewNotificationContext added in v1.1.4

func NewNotificationContext(ctx context.Context) context.Context

NewNotificationContext creates new context with JSONRPC2 notification flag. Deprecated: use appkit.NewNotificationContext.

func NewPlatformContext added in v1.1.0

func NewPlatformContext(ctx context.Context, platform string) context.Context

NewPlatformContext creates new context with platform. Deprecated: use appkit.NewPlatformContext.

func NewSQLGroupContext added in v1.2.0

func NewSQLGroupContext(ctx context.Context, group string) context.Context

NewSQLGroupContext creates new context with SQL Group for debug SQL logging. Deprecated: use appkit.NewSQLGroupContext.

func NewSQLQueryLogger added in v1.2.0

func NewSQLQueryLogger() *sqlQueryLogger

func NewUserAgentContext added in v1.1.0

func NewUserAgentContext(ctx context.Context, ua string) context.Context

NewUserAgentContext creates new context with User-Agent. Deprecated: use appkit.NewUserAgentContext.

func NewVersionContext added in v1.1.0

func NewVersionContext(ctx context.Context, version string) context.Context

NewVersionContext creates new context with version. Deprecated: use appkit.NewVersionContext.

func NewXRequestIDContext added in v1.1.0

func NewXRequestIDContext(ctx context.Context, requestID string) context.Context

NewXRequestIDContext creates new context with X-Request-ID. Deprecated: use appkit.NewXRequestIDContext.

func NotificationFromContext added in v1.1.4

func NotificationFromContext(ctx context.Context) bool

NotificationFromContext returns JSONRPC2 notification flag from context. Deprecated: use appkit.NotificationFromContext.

func PlatformFromContext

func PlatformFromContext(ctx context.Context) string

PlatformFromContext returns platform from context. Deprecated: use appkit.PlatformFromContext.

func SQLGroupFromContext added in v1.2.0

func SQLGroupFromContext(ctx context.Context) string

SQLGroupFromContext returns sql group from context. Deprecated: use appkit.SQLGroupFromContext.

func UserAgentFromContext

func UserAgentFromContext(ctx context.Context) string

UserAgentFromContext returns userAgent from context. Deprecated: use appkit.UserAgentFromContext.

func VersionFromContext

func VersionFromContext(ctx context.Context) string

VersionFromContext returns version from context. Deprecated: use appkit.VersionFromContext.

func WithAPILogger

func WithAPILogger(pf Printf, serverName string) zenrpc.MiddlewareFunc

WithAPILogger logs via Printf function (e.g. log.Printf) all requests.

func WithDevel

func WithDevel(isDevel bool) zenrpc.MiddlewareFunc

WithDevel sets bool flag to context for detecting development environment.

func WithErrorLogger

func WithErrorLogger(pf Printf, serverName string) zenrpc.MiddlewareFunc

WithErrorLogger logs all errors (ErrorCode==500 or < 0) via Printf func and sends them to Sentry. It also removes sensitive error data from response. It is good to use pkg/errors for stack trace support in sentry.

func WithErrorSLog added in v1.2.0

func WithErrorSLog(pf Print, serverName string, fn LogAttrs) zenrpc.MiddlewareFunc

WithErrorSLog logs all errors (ErrorCode==500 or < 0) via [slog.ErrorContext] func and sends them to Sentry. It also removes sensitive error data from response. It is good to use pkg/errors for stack trace support in sentry.

func WithHeaders

func WithHeaders() zenrpc.MiddlewareFunc

WithHeaders sets User-Agent, Platform, Version, X-Country headers to context. User-Agent strips to 2048 chars, Platform and Version – to 64, X-Country - to 16.

func WithMetrics

func WithMetrics(serverName string) zenrpc.MiddlewareFunc

WithMetrics logs duration of RPC requests via Prometheus. Default serverName is rpc will be in server label. It exposes two metrics: `app_rpc_error_requests_total` and `app_rpc_responses_duration_seconds`. Labels: method, code, platform, version, server.

func WithNoCancelContext

func WithNoCancelContext() zenrpc.MiddlewareFunc

WithNoCancelContext ignores Cancel func from context. This is useful for passing context to `go-pg`.

func WithSLog added in v1.2.0

func WithSLog(pf Print, serverName string, fn LogAttrs) zenrpc.MiddlewareFunc

WithSLog logs via slog function (e.g. slog.InfoContext) all requests.

func WithSQLLogger

func WithSQLLogger(db *pg.DB, isDevel bool, allowDebugFunc, allowSQLDebugFunc AllowDebugFunc) zenrpc.MiddlewareFunc

WithSQLLogger adds `SQL` or `DurationSQL` fields in JSON-RPC 2.0 Response `extensions` field (not in spec). `DurationSQL` field is set then `isDevel=true` or AllowDebugFunc(allowDebugFunc) returns `true` and http request is set. `SQL` field is set then `isDevel=true` or AllowDebugFunc(allowDebugFunc, allowSQLDebugFunc) returns `true` and http request is set.

func WithSentry

func WithSentry(serverName string) zenrpc.MiddlewareFunc

WithSentry sets additional parameters for current Sentry scope. Extras: params, duration, ip. Tags: platform, version, method. It's also handles panic.

func WithTiming

func WithTiming(isDevel bool, allowDebugFunc AllowDebugFunc) zenrpc.MiddlewareFunc

WithTiming adds timings in JSON-RPC 2.0 Response via `extensions` field (not in spec). Middleware is active when `isDevel=true` or AllowDebugFunc returns `true` and http request is set. `DurationLocal` – total method execution time in ms. If `DurationRemote` or `DurationDiff` are set then `DurationLocal` excludes these values.

func XRequestIDFromContext added in v1.1.0

func XRequestIDFromContext(ctx context.Context) string

XRequestIDFromContext returns X-Request-ID from context. Deprecated: use appkit.XRequestIDFromContext.

Types

type AllowDebugFunc

type AllowDebugFunc func(*http.Request) bool

type Duration

type Duration struct {
	time.Duration
}

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

type LogAttrs added in v1.2.0

type LogAttrs func(ctx context.Context, r zenrpc.Response) []any

type Print added in v1.2.0

type Print func(ctx context.Context, msg string, args ...any)

type Printf

type Printf func(format string, v ...interface{})

Jump to

Keyboard shortcuts

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