From 818a0e635622d3817ed94cf7ff75d1750bbe571e Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Wed, 22 Sep 2021 01:07:27 +0300 Subject: [PATCH] codec: add context helper funcs Signed-off-by: Vasiliy Tolstov --- codec/context.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 codec/context.go diff --git a/codec/context.go b/codec/context.go new file mode 100644 index 00000000..cd479172 --- /dev/null +++ b/codec/context.go @@ -0,0 +1,34 @@ +package codec + +import ( + "context" +) + +type codecKey struct{} + +// FromContext returns codec from context +func FromContext(ctx context.Context) (Codec, bool) { + if ctx == nil { + return nil, false + } + c, ok := ctx.Value(codecKey{}).(Codec) + return c, ok +} + +// NewContext put codec in context +func NewContext(ctx context.Context, c Codec) context.Context { + if ctx == nil { + ctx = context.Background() + } + return context.WithValue(ctx, codecKey{}, c) +} + +// SetOption returns a function to setup a context with given value +func SetOption(k, v interface{}) Option { + return func(o *Options) { + if o.Context == nil { + o.Context = context.Background() + } + o.Context = context.WithValue(o.Context, k, v) + } +}