middleware

package module
v1.1.6 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2024 License: MIT Imports: 17 Imported by: 2

README

zenrpc-middleware: Middlewares for vmkteam/zenrpc

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"
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 AppName is zenrpc. It exposes two metrics: appName_rpc_error_requests_count and appName_rpc_responses_duration_seconds. Labels: method, code, platform, version.

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.

ip= platform="Test1" version="v1.0.0 alpha1" method=errordevel.arith.checkzenrpcerror duration=30.786µs params=[ true ] err="test"
XRequestID

Handler for adding X-Request-ID header to all requests and responses.

	s := http.NewServer(middleware.XRequestID(http.HandlerFunc(rpc.ServeHTTP)))
EchoIPContext

Echo middleware for adding client IP info to context for zenrpc middleware

    e.Use(middleware.EchoIPContext())
EchoSentryHubContext

Echo middleware for adding sentry hub info to context for zenrpc middleware

    e.Use(middleware.EchoSentryHubContext())

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
Handler snippets
// sentry init
sentry.Init(sentry.ClientOptions{
    Dsn:         cfg.Sentry.DSN,
    Environment: cfg.Sentry.Environment,
    Release:     version,
}

// sentry middleware for Echo
e.Use(sentryecho.New(sentryecho.Options{
    Repanic:         true,
    WaitForDelivery: true,
}))

// register handler
a.echo.Any("/v1/rpc/", middleware.EchoHandler(rpc))

---  OR ---

e.Use(middleware.EchoIPContext()), middleware.EchoSentryHubContext())
// register handler
e.Any("/int/rpc/", echo.WrapHandler(XRequestID(rpc)))

Documentation

Index

Constants

View Source
const (
	DefaultServerName = ""
)

Variables

This section is empty.

Functions

func CORS

func CORS(next http.Handler) http.Handler

CORS allows certain CORS headers.

func CountryFromContext added in v1.1.6

func CountryFromContext(ctx context.Context) string

CountryFromContext returns country from context.

func DebugIDFromContext added in v1.1.1

func DebugIDFromContext(ctx context.Context) uint64

func EchoHandler

func EchoHandler(next http.Handler) echo.HandlerFunc

EchoHandler is wrapper for Echo.

func EchoIPContext added in v1.1.3

func EchoIPContext() echo.MiddlewareFunc

EchoIPContext middleware applies client ip to context for zenrpc middleware.

func EchoSentryHubContext added in v1.1.3

func EchoSentryHubContext() echo.MiddlewareFunc

EchoSentryHubContext middleware applies sentry hub to context for zenrpc middleware.

func IPFromContext

func IPFromContext(ctx context.Context) string

IPFromContext returns IP from context.

func IsDevelFromContext

func IsDevelFromContext(ctx context.Context) bool

IsDevelFromContext returns isDevel flag from context.

func NewCountryContext added in v1.1.6

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

NewCountryContext creates new context with country.

func NewDebugIDContext added in v1.1.1

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

NewDebugIDContext creates new context with debug ID.

func NewIPContext

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

NewIPContext creates new context with IP.

func NewIsDevelContext added in v1.1.1

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

NewIsDevelContext creates new context with isDevel flag.

func NewNotificationContext added in v1.1.4

func NewNotificationContext(ctx context.Context) context.Context

NewNotificationContext creates new context with JSONRPC2 notification flag.

func NewPlatformContext added in v1.1.0

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

NewPlatformContext creates new context with platform.

func NewSentryHubContext

func NewSentryHubContext(ctx context.Context, sentryHub *sentry.Hub) context.Context

NewSentryHubContext creates new context with Sentry Hub.

func NewSqlGroupContext added in v1.1.0

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

NewSqlGroupContext creates new context with SQL Group for debug SQL logging.

func NewSqlQueryLogger added in v1.1.1

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.

func NewVersionContext added in v1.1.0

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

NewVersionContext creates new context with version.

func NewXRequestIDContext added in v1.1.0

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

NewXRequestIDContext creates new context with X-Request-ID.

func NotificationFromContext added in v1.1.4

func NotificationFromContext(ctx context.Context) bool

NotificationFromContext returns JSONRPC2 notification flag from context.

func PlatformFromContext

func PlatformFromContext(ctx context.Context) string

PlatformFromContext returns platform from context.

func SqlGroupFromContext added in v1.1.1

func SqlGroupFromContext(ctx context.Context) string

SqlGroupFromContext returns sql group from context.

func UserAgentFromContext

func UserAgentFromContext(ctx context.Context) string

UserAgentFromContext returns userAgent from context.

func VersionFromContext

func VersionFromContext(ctx context.Context) string

VersionFromContext returns version from context.

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 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(appName string) zenrpc.MiddlewareFunc

WithMetrics logs duration of RPC requests via Prometheus. Default AppName is zenrpc. It exposes two metrics: `appName_rpc_error_requests_count` and `appName_rpc_responses_duration_seconds`. Labels: method, code, platform, version.

func WithNoCancelContext

func WithNoCancelContext() zenrpc.MiddlewareFunc

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

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.

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 XRequestID added in v1.1.0

func XRequestID(next http.Handler) http.Handler

XRequestID add X-Request-ID header if not exists.

func XRequestIDFromContext added in v1.1.0

func XRequestIDFromContext(ctx context.Context) string

XRequestIDFromContext returns X-Request-ID from context.

Types

type AllowDebugFunc

type AllowDebugFunc func(*http.Request) bool

type Duration

type Duration struct {
	time.Duration
}

func (Duration) MarshalJSON

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

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