From 1cc621e2d61dfe408ab98d7f5a86edfad4f22c3a Mon Sep 17 00:00:00 2001 From: Asim Date: Thu, 28 Jan 2016 18:23:24 +0000 Subject: [PATCH] FromContext/NewContext methods --- client/context.go | 16 ++++++++++++++++ go-micro.go | 13 +++++++++++++ server/context.go | 16 ++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 client/context.go create mode 100644 server/context.go diff --git a/client/context.go b/client/context.go new file mode 100644 index 00000000..d1ecdfd0 --- /dev/null +++ b/client/context.go @@ -0,0 +1,16 @@ +package client + +import ( + "golang.org/x/net/context" +) + +type clientKey struct{} + +func FromContext(ctx context.Context) (Client, bool) { + c, ok := ctx.Value(clientKey{}).(Client) + return c, ok +} + +func NewContext(ctx context.Context, c Client) context.Context { + return context.WithValue(ctx, clientKey{}, c) +} diff --git a/go-micro.go b/go-micro.go index b8ac7fe9..6defa0b8 100644 --- a/go-micro.go +++ b/go-micro.go @@ -22,8 +22,12 @@ package micro import ( "github.com/micro/go-micro/client" "github.com/micro/go-micro/server" + + "golang.org/x/net/context" ) +type serviceKey struct{} + // Service is an interface that wraps the lower level libraries // within go-micro. Its a convenience method for building // and initialising services. @@ -45,3 +49,12 @@ var ( func NewService(opts ...Option) Service { return newService(opts...) } + +func FromContext(ctx context.Context) (Service, bool) { + s, ok := ctx.Value(serviceKey{}).(Service) + return s, ok +} + +func NewContext(ctx context.Context, s Service) context.Context { + return context.WithValue(ctx, serviceKey{}, s) +} diff --git a/server/context.go b/server/context.go new file mode 100644 index 00000000..88d19257 --- /dev/null +++ b/server/context.go @@ -0,0 +1,16 @@ +package server + +import ( + "golang.org/x/net/context" +) + +type serverKey struct{} + +func FromContext(ctx context.Context) (Server, bool) { + c, ok := ctx.Value(serverKey{}).(Server) + return c, ok +} + +func NewContext(ctx context.Context, s Server) context.Context { + return context.WithValue(ctx, serverKey{}, s) +}