{"modulePath":"github.com/AlaudaDevops/distribution","version":"v2.8.3+incompatible","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package context\n\nPackage context provides several utilities for working with Go's context in http requests. Primarily, the focus is on logging relevant request information but this package is not limited to that purpose.\n\nThe easiest way to get started is to get the background context:\n\n\tctx := context.Background()\n\nThe returned context should be passed around your application and be the root of all other context instances. If the application has a version, this line should be called before anything else:\n\n\tctx := context.WithVersion(context.Background(), version)\n\nThe above will store the version in the context and will be available to the logger.\n\n### Logging {#hdr-Logging}\n\nThe most useful aspect of this package is GetLogger. This function takes any context.Context interface and returns the current logger from the context. Canonical usage looks like this:\n\n\tGetLogger(ctx).Infof(\"something interesting happened\")\n\nGetLogger also takes optional key arguments. The keys will be looked up in the context and reported with the logger. The following example would return a logger that prints the version with each log message:\n\n\tctx := context.Context(context.Background(), \"version\", version)\n\tGetLogger(ctx, \"version\").Infof(\"this log message has a version field\")\n\nThe above would print out a log message like this:\n\n\tINFO[0000] this log message has a version field        version=v2.0.0-alpha.2.m\n\nWhen used with WithLogger, we gain the ability to decorate the context with loggers that have information from disparate parts of the call stack. Following from the version example, we can build a new context with the configured logger such that we always print the version field:\n\n\tctx = WithLogger(ctx, GetLogger(ctx, \"version\"))\n\nSince the logger has been pushed to the context, we can now get the version field for free with our log messages. Future calls to GetLogger on the new context will have the version field:\n\n\tGetLogger(ctx).Infof(\"this log message has a version field\")\n\nThis becomes more powerful when we start stacking loggers. Let's say we have the version logger from above but also want a request id. Using the context above, in our request scoped function, we place another logger in the context:\n\n\tctx = context.WithValue(ctx, \"http.request.id\", \"unique id\") // called when building request context\n\tctx = WithLogger(ctx, GetLogger(ctx, \"http.request.id\"))\n\nWhen GetLogger is called on the new context, \"http.request.id\" will be included as a logger field, along with the original \"version\" field:\n\n\tINFO[0000] this log message has a version field        http.request.id=unique id version=v2.0.0-alpha.2.m\n\nNote that this only affects the new context, the previous context, with the version field, can be used independently. Put another way, the new logger, added to the request context, is unique to that context and can have request scoped variables.\n\n### HTTP Requests {#hdr-HTTP_Requests}\n\nThis package also contains several methods for working with http requests. The concepts are very similar to those described above. We simply place the request in the context using WithRequest. This makes the request variables available. GetRequestLogger can then be called to get request specific variables in a log line:\n\n\tctx = WithRequest(ctx, req)\n\tGetRequestLogger(ctx).Infof(\"request variables\")\n\nLike above, if we want to include the request data in all log messages in the context, we push the logger to a new context and use that one:\n\n\tctx = WithLogger(ctx, GetRequestLogger(ctx))\n\nThe concept is fairly powerful and ensures that calls throughout the stack can be traced in log messages. Using the fields like \"http.request.id\", one can analyze call flow for a particular request with a simple grep of the logs.\n\n## Variables\n\n```go\nvar (\n\tErrNoRequestContext        = errors.New(\"no http request in context\")\n\tErrNoResponseWriterContext = errors.New(\"no http response in context\")\n)\n```\nCommon errors used with this package.\n\n## Functions\n\n```go\nfunc Background() context.Context\n```\nBackground returns a non-nil, empty Context. The background context provides a single key, \"instance.id\" that is globally unique to the process.\n\n```go\nfunc GetRequest(ctx context.Context) (*http.Request, error)\n```\nGetRequest returns the http request in the given context. Returns ErrNoRequestContext if the context does not have an http request associated with it.\n\n```go\nfunc GetRequestID(ctx context.Context) string\n```\nGetRequestID attempts to resolve the current request id, if possible. An error is return if it is not available on the context.\n\n```go\nfunc GetResponseWriter(ctx context.Context) (http.ResponseWriter, error)\n```\nGetResponseWriter returns the http.ResponseWriter from the provided context. If not present, ErrNoResponseWriterContext is returned. The returned instance provides instrumentation in the context.\n\n```go\nfunc GetStringValue(ctx context.Context, key interface{}) (value string)\n```\nGetStringValue returns a string value from the context. The empty string will be returned if not found.\n\n```go\nfunc GetVersion(ctx context.Context) string\n```\nGetVersion returns the application version from the context. An empty string may returned if the version was not set on the context.\n\n```go\nfunc RemoteAddr(r *http.Request) string\n```\nRemoteAddr extracts the remote address of the request, taking into account proxy headers.\n\n```go\nfunc RemoteIP(r *http.Request) string\n```\nRemoteIP extracts the remote IP of the request, taking into account proxy headers.\n\n```go\nfunc Since(ctx context.Context, key interface{}) time.Duration\n```\nSince looks up key, which should be a time.Time, and returns the duration since that time. If the key is not found, the value returned will be zero. This is helpful when inferring metrics related to context execution times.\n\n```go\nfunc WithLogger(ctx context.Context, logger Logger) context.Context\n```\nWithLogger creates a new context with provided logger.\n\n```go\nfunc WithRequest(ctx context.Context, r *http.Request) context.Context\n```\nWithRequest places the request on the context. The context of the request is assigned a unique id, available at \"http.request.id\". The request itself is available at \"http.request\". Other common attributes are available under the prefix \"http.request.\". If a request is already present on the context, this method will panic.\n\n```go\nfunc WithResponseWriter(ctx context.Context, w http.ResponseWriter) (context.Context, http.ResponseWriter)\n```\nWithResponseWriter returns a new context and response writer that makes interesting response statistics available within the context.\n\n```go\nfunc WithTrace(ctx context.Context) (context.Context, func(format string, a ...interface{}))\n```\nWithTrace allocates a traced timing span in a new context. This allows a caller to track the time between calling WithTrace and the returned done function. When the done function is called, a log message is emitted with a \"trace.duration\" field, corresponding to the elapsed time and a \"trace.func\" field, corresponding to the function that called WithTrace.\n\nThe logging keys \"trace.id\" and \"trace.parent.id\" are provided to implement dapper-like tracing. This function should be complemented with a WithSpan method that could be used for tracing distributed RPC calls.\n\nThe main benefit of this function is to post-process log messages or intercept them in a hook to provide timing data. Trace ids and parent ids can also be linked to provide call tracing, if so required.\n\nHere is an example of the usage:\n\n\tfunc timedOperation(ctx Context) {\n\t\tctx, done := WithTrace(ctx)\n\t\tdefer done(\"this will be the log message\")\n\t\t// ... function body ...\n\t}\n\nIf the function ran for roughly 1s, such a usage would emit a log message as follows:\n\n\tINFO[0001] this will be the log message  trace.duration=1.004575763s trace.func=github.com/docker/distribution/context.traceOperation trace.id=\u003cid\u003e ...\n\nNotice that the function name is automatically resolved, along with the package and a trace id is emitted that can be linked with parent ids.\n\n```go\nfunc WithValues(ctx context.Context, m map[string]interface{}) context.Context\n```\nWithValues returns a context that proxies lookups through a map. Only supports string keys.\n\n```go\nfunc WithVars(ctx context.Context, r *http.Request) context.Context\n```\nWithVars extracts gorilla/mux vars and makes them available on the returned context. Variables are available at keys with the prefix \"vars.\". For example, if looking for the variable \"name\", it can be accessed as \"vars.name\". Implementations that are accessing values need not know that the underlying context is implemented with gorilla/mux vars.\n\n```go\nfunc WithVersion(ctx context.Context, version string) context.Context\n```\nWithVersion stores the application version in the context. The new context gets a logger to ensure log messages are marked with the application version.\n\n## Types\n\n```go\ntype Logger interface {\n\t// standard logger methods\n\tPrint(args ...interface{})\n\tPrintf(format string, args ...interface{})\n\tPrintln(args ...interface{})\n\n\tFatal(args ...interface{})\n\tFatalf(format string, args ...interface{})\n\tFatalln(args ...interface{})\n\n\tPanic(args ...interface{})\n\tPanicf(format string, args ...interface{})\n\tPanicln(args ...interface{})\n\n\t// Leveled methods, from logrus\n\tDebug(args ...interface{})\n\tDebugf(format string, args ...interface{})\n\tDebugln(args ...interface{})\n\n\tError(args ...interface{})\n\tErrorf(format string, args ...interface{})\n\tErrorln(args ...interface{})\n\n\tInfo(args ...interface{})\n\tInfof(format string, args ...interface{})\n\tInfoln(args ...interface{})\n\n\tWarn(args ...interface{})\n\tWarnf(format string, args ...interface{})\n\tWarnln(args ...interface{})\n\n\tWithError(err error) *logrus.Entry\n}\n```\nLogger provides a leveled-logging interface.\n\n```go\nfunc GetLogger(ctx context.Context, keys ...interface{}) Logger\n```\nGetLogger returns the logger from the current context, if present. If one or more keys are provided, they will be resolved on the context and included in the logger. While context.Value takes an interface, any key argument passed to GetLogger will be passed to fmt.Sprint when expanded as a logging key field. If context keys are integer constants, for example, its recommended that a String method is implemented.\n\n```go\nfunc GetLoggerWithField(ctx context.Context, key, value interface{}, keys ...interface{}) Logger\n```\nGetLoggerWithField returns a logger instance with the specified field key and value without affecting the context. Extra specified keys will be resolved from the context.\n\n```go\nfunc GetLoggerWithFields(ctx context.Context, fields map[interface{}]interface{}, keys ...interface{}) Logger\n```\nGetLoggerWithFields returns a logger instance with the specified fields without affecting the context. Extra specified keys will be resolved from the context.\n\n```go\nfunc GetRequestLogger(ctx context.Context) Logger\n```\nGetRequestLogger returns a logger that contains fields from the request in the current context. If the request is not available in the context, no fields will display. Request loggers can safely be pushed onto the context.\n\n```go\nfunc GetResponseLogger(ctx context.Context) Logger\n```\nGetResponseLogger reads the current response stats and builds a logger. Because the values are read at call time, pushing a logger returned from this function on the context will lead to missing or invalid data. Only call this at the end of a request, after the response has been written.\n\n","path":"github.com/AlaudaDevops/distribution/context","name":"context","synopsis":"Package context provides several utilities for working with Go's context in http requests.","isRedistributable":true}
