ctxdata

package module
v0.0.0-...-29097b9 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2019 License: Apache-2.0 Imports: 4 Imported by: 0

README

ctxdata GoDoc builds.sr.ht status

A helper for collecting and emitting metadata throughout a request lifecycle.

When a new request arrives in your program, HTTP server, etc., use the New constructor with the incoming request's context to construct a new, empty Data.

func handler(w http.ResponseWriter, r *http.Request) {
    ctx, d := ctxdata.New(r.Context())

Use the returned context for all further operations on that request.

    otherHandler(w, r.WithContext(ctx))
    result, err := process(ctx, r.Header.Get("X-My-Key"))
    // etc.

Whenever you want to add metadata to the request Data, use the From helper to fetch the Data from the context, and call whatever method is appropriate.

func otherHandler(w http.ResponseWriter, r *http.Request) {
    d := ctxdata.From(r.Context())
    d.Set("user", r.URL.Query().Get("user"))
    d.Set("corrleation_id", r.Header.Get("X-Correlation-ID"))
    // ...
}

func process(ctx context.Context, key string) {
    begin := time.Now()
    // ...
    ctxdata.From(ctx).Set("process_duration", time.Since(begin).String())
}

At the end of the request, all of the metadata collected throughout the request's lifecycle will be available.

    fmt.Fprintln(w, "OK")
    
    for k, v := range d {
        log.Printf("%s: %s", k, v)
    }
}

Here is an example middleware that writes a so-called wide event in JSON to the dst at the end of each request.

func logMiddleware(next http.Handler, dst io.Writer) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx, d := ctxdata.New(r.Context())
        defer func() { json.NewEncoder(dst).Encode(d.GetAll()) }()
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

Documentation

Overview

Package ctxdata provides a helper type for request-scoped metadata.

Index

Constants

This section is empty.

Variables

View Source
var ErrNilData = errors.New("nil data (no data in context?)")

ErrNilData is returned by certain methods on the Data type when they're called with a nil pointer receiver. This can happen when methods are chained with the From helper, and indicates a Data object wasn't found in the context.

Functions

This section is empty.

Types

type Data

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

Data is an opaque type that can be injected into a context at the start of a request, updated with metadata over the course of the request, and queried at the end of the request for collected metadata.

When a new request arrives in your program, HTTP server, etc., use the New constructor with the incoming request's context to construct a new, empty Data. Use the returned context for all further operations on that request, and use the From helper to retrieve the request's Data and set or get metadata. At the end of the request, all metadata collected will be available from any point in the callstack.

func From

func From(ctx context.Context) *Data

From extracts a Data object from the provided context. If no Data object was injected to the context, the returned pointer will be nil, but all Data methods gracefully handle this situation, so it's safe to chain.

func New

func New(ctx context.Context) (context.Context, *Data)

New constructs a Data object and injects it into the provided context. Use the returned context for all further operations in this request lifecycle. The returned Data object can be directly queried for metadata collected over the life of the request.

func (*Data) Get

func (d *Data) Get(key string) (value string, ok bool)

Get the value of key.

func (*Data) GetAll

func (d *Data) GetAll() map[string]string

GetAll returns a copy of all of the keys and values currently stored as an unordered map.

func (*Data) GetAllSlice

func (d *Data) GetAllSlice() []KeyValue

GetAllSlice returns a copy of all of the keys and values currently stored as a slice of KeyValues, in the order they were added (set).

func (*Data) GetDefault

func (d *Data) GetDefault(key, defaultValue string) (value string)

GetDefault returns the value of key, or defaultValue if no value is available.

func (*Data) Set

func (d *Data) Set(key, value string) error

Set key to value.

func (*Data) Walk

func (d *Data) Walk(fn func(key, value string) error) error

Walk calls fn for each key and value currently stored in the order they were added (set). If fn returns a non-nil error, Walk aborts with that error.

type KeyValue

type KeyValue struct {
	Key   string
	Value string
}

KeyValue simply combines a key and its value.

Jump to

Keyboard shortcuts

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