pkgsite: golang.org/x/pkgsite/internal/middleware Index | Files

package middleware

import "golang.org/x/pkgsite/internal/middleware"

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

Index

Package Files

accept_requests.go caching.go errorreporting.go experiment.go godoc.go iapheader.go latestversion.go middleware.go panic.go quota.go requestlog.go secureheaders.go stats.go timeout.go

Constants

const (
    LatestMinorVersionPlaceholder = "$$GODISCOVERY_LATESTMINORVERSION$$"

    LatestMajorVersionPlaceholder = "$$GODISCOVERY_LATESTMAJORVERSION$$"
    LatestMajorVersionURL         = "$$GODISCOVERY_LATESTMAJORVERSIONURL$$"
)
const GodocURLPlaceholder = "$$GODISCOVERY_GODOCURL$$"

GodocURLPlaceholder should be used as the value for any godoc.org URL in rendered content. It is substituted for the actual godoc.org URL value by the GodocURL middleware.

Variables

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},
    }
)
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 Uses

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 SetStat Uses

func SetStat(ctx context.Context, key string, value interface{})

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 Uses

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

ExperimentGetter is the signature of a function that gets experiments.

type Experimenter Uses

type Experimenter struct {
    // contains filtered or unexported fields
}

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

func NewExperimenter Uses

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 Uses

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

Experiments returns the experiments currently in use.

type Expirer Uses

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

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

func TTL Uses

func TTL(ttl time.Duration) Expirer

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

type LocalLogger Uses

type LocalLogger struct{}

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

func (LocalLogger) Log Uses

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

Log implements the Logger interface via our internal log package.

type Logger Uses

type Logger interface {
    Log(logging.Entry)
}

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

type Middleware Uses

type Middleware func(http.Handler) http.Handler

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

func AcceptRequests Uses

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 Cache Uses

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 Uses

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 Uses

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

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

func Experiment Uses

func Experiment(e *Experimenter) Middleware

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

func GodocURL Uses

func GodocURL() Middleware

GodocURL adds a corresponding godoc.org URL value to the rendered page if the request is due to godoc.org automatically redirecting a user. The value is empty otherwise.

func Identity Uses

func Identity() Middleware

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

func LatestVersions Uses

func LatestVersions(latestMinor latestMinorFunc, latestMajor latestMajorFunc) Middleware

LatestVersions replaces the HTML placeholder values for the badge and banner that displays whether the version of the package or module being served is the latest minor version (badge) and the latest major version (banner).

func Panic Uses

func Panic(panicHandler http.Handler) Middleware

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

func Quota Uses

func Quota(settings config.QuotaSettings) Middleware

Quota implements a simple IP-based rate limiter. Each set of incoming IP addresses with the same low-order byte gets qps requests per second, with the given burst. Information is kept in an LRU cache of size maxEntries.

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

func RequestLog Uses

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 Uses

func SecureHeaders(enableCSP bool) Middleware

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

func Stats Uses

func Stats() Middleware

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

func Timeout Uses

func Timeout(d time.Duration) Middleware

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

func ValidateIAPHeader Uses

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 Uses

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]interface{}
}

type Reporter Uses

type Reporter interface {
    Report(errorreporting.Entry)
}

A Reporter sends errors to the Error-Reporting service.

Package middleware imports 34 packages (graph) and is imported by 9 packages. Updated 2020-10-28. Refresh now. Tools for package owners.