Browse Source

添加从上下文获取方法

lxg 3 years ago
parent
commit
b3b4930778
1 changed files with 18 additions and 0 deletions
  1. 18 0
      crud.go

+ 18 - 0
crud.go

@@ -1,6 +1,7 @@
 package rest
 
 import (
+	"context"
 	"fmt"
 	"git.nspix.com/golang/micro/gateway/http"
 	"git.nspix.com/golang/micro/log"
@@ -26,6 +27,12 @@ type (
 		Value    string       `json:"value"`
 		Children []*treeValue `json:"children"`
 	}
+
+	contextKey struct{}
+)
+
+var (
+	ctxKey = contextKey{}
 )
 
 func (t *treeValue) Append(v *treeValue) {
@@ -272,3 +279,14 @@ func Dialer(cfg *Config) (crud *CRUD, err error) {
 	}
 	return
 }
+
+func FromContext(ctx context.Context) *CRUD {
+	if v := ctx.Value(ctxKey); v != nil {
+		return v.(*CRUD)
+	}
+	return nil
+}
+
+func WithContext(ctx context.Context, r *CRUD) context.Context {
+	return context.WithValue(ctx, ctxKey, r)
+}