Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API for field package #276

Merged
merged 3 commits into from
Sep 10, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}