Documentation ¶
Overview ¶
Package ctxdata provides a helper type for request-scoped metadata.
Example (Middleware) ¶
package main import ( "fmt" "net/http" "net/http/httptest" "strings" "github.com/peterbourgon/ctxdata/v4" ) type Server struct{} func NewServer() *Server { return &Server{} } func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { d := ctxdata.From(r.Context()) d.Set("method", r.Method) d.Set("path", r.URL.Path) d.Set("content_length", r.ContentLength) fmt.Fprintln(w, "OK") } type Middleware struct { next http.Handler } func NewMiddleware(next http.Handler) *Middleware { return &Middleware{next: next} } func (mw *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx, d := ctxdata.New(r.Context()) defer func() { for _, kv := range d.GetAllSlice() { fmt.Printf("%s: %v\n", kv.Key, kv.Val) } }() mw.next.ServeHTTP(w, r.WithContext(ctx)) } func main() { server := NewServer() middleware := NewMiddleware(server) testserver := httptest.NewServer(middleware) defer testserver.Close() http.Post(testserver.URL+"/path", "text/plain; charset=utf-8", strings.NewReader("hello world")) }
Output: method: POST path: /path content_length: 11
Index ¶
- Variables
- type Data
- func (d *Data) Get(key string) (val interface{}, err error)
- func (d *Data) GetAllMap() map[string]interface{}
- func (d *Data) GetAllSlice() []KeyVal
- func (d *Data) GetAs(key string, target interface{}) error
- func (d *Data) GetBool(key string) (val bool)
- func (d *Data) GetBoolDefault(key string, defaultValue bool) bool
- func (d *Data) GetDuration(key string) (val time.Duration)
- func (d *Data) GetDurationDefault(key string, defaultValue time.Duration) time.Duration
- func (d *Data) GetError(key string) (val error)
- func (d *Data) GetErrorDefault(key string, defaultValue error) error
- func (d *Data) GetFloat64(key string) (val float64)
- func (d *Data) GetFloat64Default(key string, defaultValue float64) float64
- func (d *Data) GetInt(key string) (val int)
- func (d *Data) GetInt64(key string) (val int64)
- func (d *Data) GetInt64Default(key string, defaultValue int64) int64
- func (d *Data) GetIntDefault(key string, defaultValue int) int
- func (d *Data) GetString(key string) (val string)
- func (d *Data) GetStringDefault(key string, defaultValue string) string
- func (d *Data) GetTime(key string) (val time.Time)
- func (d *Data) GetTimeDefault(key string, defaultValue time.Time) time.Time
- func (d *Data) GetUint64(key string) (val uint64)
- func (d *Data) GetUint64Default(key string, defaultValue uint64) uint64
- func (d *Data) Set(key string, val interface{}) error
- type KeyVal
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrIncompatibleType = errors.New("incompatible type")
ErrIncompatibleType is returned by GetAs if the value associated with a key isn't assignable to the provided target.
var ErrNoData = errors.New("no data in context")
ErrNoData is returned by accessor methods when they're called on a nil pointer receiver. This typically means From was called on a context that didn't have a Data injected into it previously via New.
var ErrNotFound = errors.New("key not found")
ErrNotFound is returned by Get when the key isn't present.
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 e.g. the start of a request, updated with metadata over the course of the request, and then queried at the end of the request.
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. Use the From helper function to retrieve a previously-injected Data from a context, 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 ¶
From extracts a Data 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 condition, so it's safe to consider the returned value always valid.
func New ¶
New constructs a Data object and injects it into the provided context. Use the returned context for all further operations. The returned Data can be queried at any point for metadata collected over the life of the context.
func (*Data) Get ¶
Get the value associated with key, or return ErrNotFound. If this method is called on a nil Data pointer, it returns ErrNoData.
func (*Data) GetAllMap ¶
GetAllMap returns a map of key to value. If this method is called on a nil Data pointer, it returns ErrNoData.
func (*Data) GetAllSlice ¶
GetAllSlice returns a slice of key/value pairs in the order in which they were set. If this method is called on a nil Data pointer, it returns ErrNoData.
func (*Data) GetAs ¶
GetAs will try to assign the value associated with key to target. Target must be a pointer to an assignable type. GetAs will return ErrNotFound if the key is not found, and ErrIncompatibleType if the found value is not assignable to target.
Example ¶
This example demonstrates how to use GetAs to retrieve metadata into an arbitrary type.
type DomainError struct { Code int Reason string } _, d := ctxdata.New(context.Background()) derr := DomainError{Code: http.StatusTeapot, Reason: "Earl Gray exception"} d.Set("err", derr) if target := (DomainError{}); d.GetAs("err", &target) == nil { fmt.Printf("DomainError Code=%d Reason=%q\n", target.Code, target.Reason) }
Output: DomainError Code=418 Reason="Earl Gray exception"
func (*Data) GetBool ¶
GetBool returns the value of key as type bool. If key is not set, or its value is not of type bool, then GetBool returns a zero value of type bool.
func (*Data) GetBoolDefault ¶
GetBoolDefault returns the value of key as type bool. If key is not set, or its value is not of type bool, then GetBoolDefault returns defaultValue.
func (*Data) GetDuration ¶
GetDuration returns the value of key as type time.Duration. If key is not set, or its value is not of type time.Duration, then GetDuration returns a zero value of type time.Duration.
func (*Data) GetDurationDefault ¶
GetDurationDefault returns the value of key as type time.Duration. If key is not set, or its value is not of type time.Duration, then GetDurationDefault returns defaultValue.
func (*Data) GetError ¶
GetError returns the value of key as type error. If key is not set, or its value is not of type error, then GetError returns a zero value of type error.
func (*Data) GetErrorDefault ¶
GetErrorDefault returns the value of key as type error. If key is not set, or its value is not of type error, then GetErrorDefault returns defaultValue.
func (*Data) GetFloat64 ¶
GetFloat64 returns the value of key as type float64. If key is not set, or its value is not of type float64, then GetFloat64 returns a zero value of type float64.
func (*Data) GetFloat64Default ¶
GetFloat64Default returns the value of key as type float64. If key is not set, or its value is not of type float64, then GetFloat64Default returns defaultValue.
func (*Data) GetInt ¶
GetInt returns the value of key as type int. If key is not set, or its value is not of type int, then GetInt returns a zero value of type int.
func (*Data) GetInt64 ¶
GetInt64 returns the value of key as type int64. If key is not set, or its value is not of type int64, then GetInt64 returns a zero value of type int64.
func (*Data) GetInt64Default ¶
GetInt64Default returns the value of key as type int64. If key is not set, or its value is not of type int64, then GetInt64Default returns defaultValue.
func (*Data) GetIntDefault ¶
GetIntDefault returns the value of key as type int. If key is not set, or its value is not of type int, then GetIntDefault returns defaultValue.
func (*Data) GetString ¶
GetString returns the value of key as type string. If key is not set, or its value is not of type string, then GetString returns a zero value of type string.
func (*Data) GetStringDefault ¶
GetStringDefault returns the value of key as type string. If key is not set, or its value is not of type string, then GetStringDefault returns defaultValue.
func (*Data) GetTime ¶
GetTime returns the value of key as type time.Time. If key is not set, or its value is not of type time.Time, then GetTime returns a zero value of type time.Time.
func (*Data) GetTimeDefault ¶
GetTimeDefault returns the value of key as type time.Time. If key is not set, or its value is not of type time.Time, then GetTimeDefault returns defaultValue.
func (*Data) GetUint64 ¶
GetUint64 returns the value of key as type uint64. If key is not set, or its value is not of type uint64, then GetUint64 returns a zero value of type uint64.
func (*Data) GetUint64Default ¶
GetUint64Default returns the value of key as type uint64. If key is not set, or its value is not of type uint64, then GetUint64Default returns defaultValue.