51 lines
1.3 KiB
Go
51 lines
1.3 KiB
Go
package apapter
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/gogf/gf/v2/container/gvar"
|
|
"github.com/gogf/gf/v2/encoding/gbase64"
|
|
"github.com/gogf/gf/v2/encoding/gjson"
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
"google.golang.org/grpc/metadata"
|
|
)
|
|
|
|
/**
|
|
* @Description: ContextAdapter
|
|
* @author dc.To
|
|
* @version 20250807
|
|
*/
|
|
type ContextAdapter struct {
|
|
ctx context.Context
|
|
adapter string
|
|
}
|
|
|
|
func NewContextAdapter(ctx context.Context, adapter string) *ContextAdapter {
|
|
return &ContextAdapter{ctx: ctx, adapter: adapter}
|
|
}
|
|
|
|
func (a *ContextAdapter) ctxWithConfig(ctx context.Context) *gvar.Var {
|
|
md, ok := metadata.FromIncomingContext(ctx)
|
|
if ok {
|
|
if c := md.Get(a.adapter); len(c) > 0 {
|
|
return gvar.New(gbase64.MustDecodeToString(c[0]))
|
|
}
|
|
}
|
|
g.Log("cfg").Error(ctx, "No Metadata from ["+a.adapter+"] cfg context")
|
|
|
|
return gvar.New(nil)
|
|
}
|
|
|
|
func (a *ContextAdapter) Available(ctx context.Context, resource ...string) (ok bool) {
|
|
return a.ctxWithConfig(ctx) != nil
|
|
}
|
|
|
|
func (a *ContextAdapter) Get(ctx context.Context, pattern string) (value interface{}, err error) {
|
|
|
|
return gjson.New(a.ctxWithConfig(ctx)).Get(pattern).Val(), nil
|
|
}
|
|
|
|
func (a *ContextAdapter) Data(ctx context.Context) (data map[string]interface{}, err error) {
|
|
return gjson.New(a.ctxWithConfig(ctx)).Map(), nil
|
|
}
|