Version: v0.0.0-...-8893da0 Latest Latest

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

Go to latest
Published: Nov 23, 2022 License: BSD-3-Clause Imports: 38 Imported by: 0



Package middleware implements a simple middleware pattern for http handlers, along with implementations for some common middlewares.



This section is empty.


View Source
var (
	CacheResultCount = &view.View{
		Name:        "go-discovery/cache/result_count",
		Measure:     cacheResults,
		Aggregation: view.Count(),
		Description: "cache results, by cache name and whether it was a hit",
		TagKeys:     []tag.Key{keyCacheName, keyCacheHit},
	CacheLatency = &view.View{
		Name:        "go-discovery/cache/result_latency",
		Measure:     cacheLatency,
		Description: "cache result latency, by cache name and whether it was a hit",
		Aggregation: ochttp.DefaultLatencyDistribution,
		TagKeys:     []tag.Key{keyCacheName, keyCacheHit},
	CacheErrorCount = &view.View{
		Name:        "go-discovery/cache/errors",
		Measure:     cacheErrors,
		Aggregation: view.Count(),
		Description: "cache errors, by cache name",
		TagKeys:     []tag.Key{keyCacheName, keyCacheOperation},

	// To avoid test flakiness, when TestMode is true, cache writes are
	// synchronous.
	TestMode = false
View Source
var (

	// QuotaResultCount is a counter of quota results, by whether the request was blocked or not.
	QuotaResultCount = &view.View{
		Name:        "go-discovery/quota/result_count",
		Measure:     quotaResults,
		Aggregation: view.Count(),
		Description: "quota results, by blocked or allowed",
		TagKeys:     []tag.Key{keyQuotaBlocked},


func ElapsedStat

func ElapsedStat(ctx context.Context, name string) func()

ElapsedStat records as a stat the elapsed time for a function execution. Invoke like so:

defer ElapsedStat(ctx, "FunctionName")()

The resulting stat will be called "FunctionName ms" and will be the wall-clock execution time of the function in milliseconds.

func Language

func Language(h http.Handler) http.Handler

Language is a middleware that provides browser i18n information to handlers, in the form of a golang.org/x/text/language.Tag.

func LanguageTag

func LanguageTag(ctx context.Context) language.Tag

LanguageTag returns the language.Tag from the context, or language.English if none is set.

func SetStat

func SetStat(ctx context.Context, key string, value any)

SetStat sets a stat named key in the current context. If key already has a value, the old and new value are both stored in a slice.


type ExperimentGetter

type ExperimentGetter func(context.Context) ([]*internal.Experiment, error)

ExperimentGetter is the signature of a function that gets experiments.

type Experimenter

type Experimenter struct {
	// contains filtered or unexported fields

An Experimenter contains information about active experiments from the experiment source.

func NewExperimenter

func NewExperimenter(ctx context.Context, pollEvery time.Duration, getter ExperimentGetter, rep Reporter) (_ *Experimenter, err error)

NewExperimenter returns an Experimenter for use in the middleware. The experimenter regularly polls for updates to the snapshot in the background.

func (*Experimenter) Experiments

func (e *Experimenter) Experiments() []*internal.Experiment

Experiments returns the experiments currently in use.

type Expirer

type Expirer func(r *http.Request) time.Duration

An Expirer computes the TTL that should be used when caching a page.

func TTL

func TTL(ttl time.Duration) Expirer

TTL returns an Expirer that expires all pages after the given TTL.

type LocalLogger

type LocalLogger struct{}

LocalLogger is a logger that can be used when running locally (i.e.: not on GCP)

func (LocalLogger) Log

func (l LocalLogger) Log(entry logging.Entry)

Log implements the Logger interface via our internal log package.

type Logger

type Logger interface {

Logger is the interface used to write request logs to GCP.

type Middleware

type Middleware func(http.Handler) http.Handler

A Middleware is a func that wraps an http.Handler.

func AcceptRequests

func AcceptRequests(methods ...string) Middleware

AcceptRequests serves 405 (Method Not Allowed) for any method not on the given list and 414 (Method Request URI Too Long) for any URI that exceeds the maxURILength.

func BetaPkgGoDevRedirect

func BetaPkgGoDevRedirect() Middleware

BetaPkgGoDevRedirect redirects requests from pkg.go.dev to beta.pkg.go.dev, based on whether a cookie is set for betapkggodev-redirect. The cookie can be turned on/off using a query param.

func Cache

func Cache(name string, client *redis.Client, expirer Expirer, authValues []string) Middleware

Cache returns a new Middleware that caches every request. The name of the cache is used only for metrics. The expirer is a func that is used to map a new request to its TTL. authHeader is the header key used by the cache to know that a request should bypass the cache. authValues is the set of values that could be set on the authHeader in order to bypass the cache.

func Chain

func Chain(middlewares ...Middleware) Middleware

Chain creates a new Middleware that applies a sequence of Middlewares, so that they execute in the given order when handling an http request.

In other words, Chain(m1, m2)(handler) = m1(m2(handler))

A similar pattern is used in e.g. github.com/justinas/alice: https://github.com/justinas/alice/blob/ce87934/chain.go#L45

func ErrorReporting

func ErrorReporting(report func(errorreporting.Entry)) Middleware

ErrorReporting returns a middleware that reports any server errors using the report func.

func Experiment

func Experiment(e *Experimenter) Middleware

Experiment returns a new Middleware that sets active experiments for each incoming request.

func GodocOrgRedirect

func GodocOrgRedirect() Middleware

GodocOrgRedirect redirects requests from godoc.org to pkg.go.dev.

func Identity

func Identity() Middleware

Identity is a middleware that does nothing. It can be used as a helper when building middleware chains.

func Panic

func Panic(panicHandler http.Handler) Middleware

Panic returns a middleware that executes panicHandler on any panic originating from the delegate handler.

func Quota

func Quota(settings config.QuotaSettings, client *redis.Client) Middleware

Quota implements a simple IP-based rate limiter. Each set of incoming IP addresses with the same low-order byte gets settings.QPS requests per second.

Information is kept in a redis instance.

If a request is disallowed, a 429 (TooManyRequests) will be served.

func RequestLog

func RequestLog(lg Logger) Middleware

RequestLog returns a middleware that logs each incoming requests using the given logger. This logger replaces the built-in appengine request logger, which logged PII when behind IAP, in such a way that was impossible to turn off.

Logs may be viewed in Pantheon by selecting the log source corresponding to the AppEngine service name (e.g. 'dev-worker').

func SecureHeaders

func SecureHeaders(enableCSP bool) Middleware

SecureHeaders adds a content-security-policy and other security-related headers to all responses.

func Stats

func Stats() Middleware

Stats returns a Middleware that, instead of serving the page, serves statistics about the page.

func Timeout

func Timeout(d time.Duration) Middleware

Timeout returns a new Middleware that times out each request after the given duration.

func ValidateIAPHeader

func ValidateIAPHeader(audience string) Middleware

ValidateIAPHeader checks that the request has a header that proves it arrived via the IAP. See https://cloud.google.com/iap/docs/signed-headers-howto#securing_iap_headers.

type PageStats

type PageStats struct {
	MillisToFirstByte int64
	MillisToLastByte  int64
	Hash              uint64 // hash of page contents
	Size              int    // total size of data written
	StatusCode        int    // HTTP status
	Other             map[string]any

type Reporter

type Reporter interface {

A Reporter sends errors to the Error-Reporting service.

Jump to

Keyboard shortcuts

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