blob: d62bf9edfdbaee647d79229fbef163ae73f60512 [file] [log] [blame]
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package fxctx
import (
"context"
"encoding/json"
"fmt"
)
// ContextKey is used to store values in Context objects.
type ContextKey string
// Set associates a JSON encodable value with a key in a Context object.
func Set(ctx context.Context, key ContextKey, value interface{}) (context.Context, error) {
data, err := json.Marshal(value)
if err != nil {
return nil, err
}
return context.WithValue(ctx, key, data), nil
}
// Get reads a value from a Context into `out`. Returns true iff the given key is present
// in the Context, even if the key cannot be read into `out`.
func Get(ctx context.Context, key ContextKey, out interface{}) error {
value := ctx.Value(key)
if value == nil {
return fmt.Errorf("not found %v", key)
}
bytes, ok := value.([]byte)
if !ok {
return fmt.Errorf("expected a []byte value for %v but got %v", key, value)
}
return json.Unmarshal(bytes, out)
}