middleware

package
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2019 License: MIT Imports: 18 Imported by: 286

README

goa Middlewares

The middleware package provides middlewares that do not depend on additional packages other than the ones already used by goa. These middlewares provide functionality that is useful to most microservices:

  • LogRequest enables logging of incoming requests and corresponding responses. The log format is entirely configurable. The default format logs the request HTTP method, path and parameters as well as the corresponding action and controller names. It also logs the request duration and response length. It also logs the request payload if the DEBUG log level is enabled. Finally if the RequestID middleware is mounted LogRequest logs the unique request ID with each log entry.

  • LogResponse logs the content of the response body if the DEBUG log level is enabled.

  • RequestID injects a unique ID in the request context. This ID is used by the logger and can be used by controller actions as well. The middleware looks for the ID in the RequestIDHeader header and if not found creates one.

  • Recover recover panics and logs the panic object and backtrace.

  • Timeout sets a deadline in the request context. Controller actions may subscribe to the context channel to get notified when the timeout expires.

  • RequireHeader checks for the presence of a header in the request with a value matching a given regular expression. If the header is absent or does not match the regexp the middleware sends a HTTP response with a given HTTP status.

Other middlewares listed below are provided as separate Go packages.

Gzip

Package gzip contributed by @tylerb adds the ability to compress response bodies using gzip format as specified in RFC 1952.

Security

package security contains middleware that should be used in conjunction with the security DSL.

Documentation

Index

Constants

View Source
const (
	// RequestIDHeader is the name of the header used to transmit the request ID.
	RequestIDHeader = "X-Request-Id"

	// DefaultRequestIDLengthLimit is the default maximum length for the request ID header value.
	DefaultRequestIDLengthLimit = 128
)

Variables

View Source
var (
	// TraceIDHeader is the name of the HTTP request header containing the
	// current TraceID if any.
	TraceIDHeader = "TraceID"

	// ParentSpanIDHeader is the name of the HTTP request header containing
	// the parent span ID if any.
	ParentSpanIDHeader = "ParentSpanID"
)

Functions

func ContextParentSpanID added in v1.2.0

func ContextParentSpanID(ctx context.Context) string

ContextParentSpanID returns the parent span ID extracted from the given context if any, the empty string otherwise.

func ContextRequestID

func ContextRequestID(ctx context.Context) (reqID string)

ContextRequestID extracts the Request ID from the context.

func ContextSpanID added in v1.2.0

func ContextSpanID(ctx context.Context) string

ContextSpanID returns the span ID extracted from the given context if any, the empty string otherwise.

func ContextTraceID added in v1.2.0

func ContextTraceID(ctx context.Context) string

ContextTraceID returns the trace ID extracted from the given context if any, the empty string otherwise.

func ErrorHandler

func ErrorHandler(service *goa.Service, verbose bool) goa.Middleware

ErrorHandler turns a Go error into an HTTP response. It should be placed in the middleware chain below the logger middleware so the logger properly logs the HTTP response. ErrorHandler understands instances of goa.ServiceError and returns the status and response body embodied in them, it turns other Go error types into a 500 internal error response. If verbose is false the details of internal errors is not included in HTTP responses. If you use github.com/pkg/errors then wrapping the error will allow a trace to be printed to the logs

func LogRequest

func LogRequest(verbose bool, sensitiveHeaders ...string) goa.Middleware

LogRequest creates a request logger middleware. This middleware is aware of the RequestID middleware and if registered after it leverages the request ID for logging. If verbose is true then the middlware logs the request and response bodies.

func LogResponse

func LogResponse() goa.Middleware

LogResponse creates a response logger middleware. Only Logs the raw response data without accumulating any statistics.

func NewTracer added in v1.3.0

func NewTracer(opts ...TracerOption) goa.Middleware

NewTracer returns a trace middleware that initializes the trace information in the request context. The information can be retrieved using any of the ContextXXX functions.

samplingPercent must be a value between 0 and 100. It represents the percentage of requests that should be traced. If the incoming request has a Trace ID header then the sampling rate is disregarded and the tracing is enabled.

spanIDFunc and traceIDFunc are the functions used to create Span and Trace IDs respectively. This is configurable so that the created IDs are compatible with the various backend tracing systems. The xray package provides implementations that produce AWS X-Ray compatible IDs.

func Recover

func Recover() goa.Middleware

Recover is a middleware that recovers panics and maps them to errors.

func RequestID

func RequestID() goa.Middleware

RequestID is a middleware that injects a request ID into the context of each request. Retrieve it using ctx.Value(ReqIDKey). If the incoming request has a RequestIDHeader header then that value is used else a random value is generated.

func RequestIDWithHeader

func RequestIDWithHeader(requestIDHeader string) goa.Middleware

RequestIDWithHeader behaves like the middleware RequestID, but it takes the request id header as the (first) argument.

func RequestIDWithHeaderAndLengthLimit

func RequestIDWithHeaderAndLengthLimit(requestIDHeader string, lengthLimit int) goa.Middleware

RequestIDWithHeaderAndLengthLimit behaves like the middleware RequestID, but it takes the request id header as the (first) argument and a length limit for truncation of the request header value if it exceeds a reasonable length. The limit can be negative for unlimited.

func RequireHeader

func RequireHeader(
	service *goa.Service,
	pathPattern *regexp.Regexp,
	requiredHeaderName string,
	requiredHeaderValue *regexp.Regexp,
	failureStatus int) goa.Middleware

RequireHeader requires a request header to match a value pattern. If the header is missing or does not match then the failureStatus is the response (e.g. http.StatusUnauthorized). If pathPattern is nil then any path is included. If requiredHeaderValue is nil then any value is accepted so long as the header is non-empty.

func Timeout

func Timeout(timeout time.Duration) goa.Middleware

Timeout sets a global timeout for all controller actions. The timeout notification is made through the context, it is the responsability of the request handler to handle it. For example:

func (ctrl *Controller) DoLongRunningAction(ctx *DoLongRunningActionContext) error {
	action := NewLongRunning()      // setup long running action
	c := make(chan error, 1)        // create return channel
	go func() { c <- action.Run() } // Launch long running action goroutine
	select {
	case <- ctx.Done():             // timeout triggered
		action.Cancel()         // cancel long running action
		<-c                     // wait for Run to return.
		return ctx.Err()        // retrieve cancel reason
	case err := <-c:   		// action finished on time
		return err  		// forward its return value
	}
}

Controller actions can check if a timeout is set by calling the context Deadline method.

func TraceDoer added in v1.2.0

func TraceDoer(doer client.Doer) client.Doer

TraceDoer wraps a goa client Doer and sets the trace headers so that the downstream service may properly retrieve the parent span ID and trace ID.

func Tracer added in v1.2.0

func Tracer(sampleRate int, spanIDFunc, traceIDFunc IDFunc) goa.Middleware

Tracer is deprecated in favor of NewTracer.

func WithTrace added in v1.2.0

func WithTrace(ctx context.Context, traceID, spanID, parentID string) context.Context

WithTrace returns a context containing the given trace, span and parent span IDs.

Types

type IDFunc added in v1.2.0

type IDFunc func() string

IDFunc is a function that produces span and trace IDs for cosumption by tracing systems such as Zipkin or AWS X-Ray.

type Sampler added in v1.3.0

type Sampler interface {
	// Sample returns true if the caller should sample now.
	Sample() bool
}

Sampler is an interface for computing when a sample falls within a range.

func NewAdaptiveSampler added in v1.3.0

func NewAdaptiveSampler(maxSamplingRate, sampleSize int) Sampler

NewAdaptiveSampler computes the interval for sampling for tracing middleware. it can also be used by non-web go routines to trace internal API calls.

maxSamplingRate is the desired maximum sampling rate in requests per second.

sampleSize sets the number of requests between two adjustments of the sampling rate when MaxSamplingRate is set. the sample rate cannot be adjusted until the sample size is reached at least once.

func NewFixedSampler added in v1.3.0

func NewFixedSampler(samplingPercent int) Sampler

NewFixedSampler sets the tracing sampling rate as a percentage value.

type TracerOption added in v1.3.0

type TracerOption func(*tracerOptions) *tracerOptions

TracerOption is a constructor option that makes it possible to customize the middleware.

func MaxSamplingRate added in v1.3.0

func MaxSamplingRate(r int) TracerOption

MaxSamplingRate sets a target sampling rate in requests per second. Setting a max sampling rate causes the middleware to adjust the sampling percent dynamically. SamplingPercent and MaxSamplingRate are mutually exclusive.

func SampleSize added in v1.3.0

func SampleSize(s int) TracerOption

SampleSize sets the number of requests between two adjustments of the sampling rate when MaxSamplingRate is set. Defaults to 1,000.

func SamplingPercent added in v1.3.0

func SamplingPercent(p int) TracerOption

SamplingPercent sets the tracing sampling rate as a percentage value. It panics if p is less than 0 or more than 100. SamplingPercent and MaxSamplingRate are mutually exclusive.

func SpanIDFunc added in v1.3.0

func SpanIDFunc(f IDFunc) TracerOption

SpanIDFunc is a constructor option that overrides the function used to compute span IDs.

func TraceIDFunc added in v1.3.0

func TraceIDFunc(f IDFunc) TracerOption

TraceIDFunc is a constructor option that overrides the function used to compute trace IDs.

Directories

Path Synopsis
security
jwt

Jump to

Keyboard shortcuts

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