Skip to content

Commit

Permalink
API for field package (#276)
Browse files Browse the repository at this point in the history
Motivation: See #273 

* field.Field interface definition
* package-level functions: New, Add
* API for adding fields to context.Context
  • Loading branch information
julio-lopez committed Sep 10, 2019
1 parent 3022763 commit 38c4e27
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
29 changes: 29 additions & 0 deletions pkg/field/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package field

import "context"

// context.Context support for fields

type contextKey uint8

const ctxKey = contextKey(43)

// FromContext returns the fields present in ctx if any
func FromContext(ctx context.Context) Fields {
if s, ok := ctx.Value(ctxKey).(Fields); ok {
return s
}
return nil
}

// AddToContext returns a new context that has ctx as its parent context and
// has a Field with the given key and value.
func AddToContext(ctx context.Context, key string, v interface{}) context.Context {
return context.WithValue(ctx, ctxKey, Add(FromContext(ctx), key, v))
}

// AddMapToContext returns a context that has ctx as its parent context and has
// fields populated from the keys and values in m.
func AddMapToContext(ctx context.Context, m M) context.Context {
return context.WithValue(ctx, ctxKey, addMap(FromContext(ctx), m))
}
41 changes: 41 additions & 0 deletions pkg/field/field.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package field

// Field is a tuple with a string key and a value of any type
type Field interface {
Key() string
Value() interface{}
}

// Fieldser is a collection of fields
type Fieldser interface {
Fields() []Field
}

// Fields is an alias for Fieldser to make the interface friendlier. It seems
// easier to talk about fields than fieldser(s)
type Fields = Fieldser

// New creates a new field collection with given key and value
func New(key string, value interface{}) Fields {
return Add(nil, key, value)
}

// Add returns a collection with all the fields in s plus a new field with the
// given key and value. Duplicates are not eliminated.
func Add(s Fields, key string, value interface{}) Fields {
// TODO: implement
return nil
}

// M contains fields with unique keys. Used to facilitate adding multiple
// "fields" to a Fields collection
type M = map[string]interface{}

// addMap adds the entries in m to s as Field(s). The map key is used as the
// Field.Key() and the corresponding value as Field.Value()
func addMap(s Fields, m M) Fields {
for k, v := range m {
s = Add(s, k, v)
}
return s
}

0 comments on commit 38c4e27

Please sign in to comment.