github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/log/tapper/notice_ctx.go (about) 1 package tapper 2 3 import ( 4 "context" 5 "fmt" 6 "sync" 7 8 hack "github.com/weedge/lib/strings" 9 10 "github.com/gin-gonic/gin" 11 jsoniter "github.com/json-iterator/go" 12 ) 13 14 const ( 15 NOTICECTX = "NOTICECTX" 16 ) 17 18 type Notice struct { 19 data map[string]interface{} 20 mu sync.Mutex 21 } 22 23 func (notice *Notice) Marshal() string { 24 notice.mu.Lock() 25 defer notice.mu.Unlock() 26 27 b, _ := jsoniter.MarshalToString(notice.data) 28 return b 29 } 30 func (notice *Notice) Push(args ...interface{}) *Notice { 31 notice.mu.Lock() 32 defer notice.mu.Unlock() 33 34 for i := 0; i < len(args)-1; i += 2 { 35 switch args[i+1].(type) { 36 case string, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: 37 notice.data[fmt.Sprintf("%v", args[i])] = args[i+1] 38 default: 39 if b, e := jsoniter.Marshal(args[i+1]); e == nil { 40 notice.data[fmt.Sprintf("%v", args[i])] = hack.String(b) 41 } 42 } 43 } 44 return notice 45 } 46 47 func GetNoticeFromContext(ctx context.Context) (context.Context, *Notice) { 48 switch c := ctx.(type) { 49 case *gin.Context: 50 if notice, ok := c.Get(NOTICECTX); ok && notice != nil { 51 if notice, ok := notice.(*Notice); ok && notice != nil { 52 return ctx, notice 53 } 54 } 55 56 notice := &Notice{data: map[string]interface{}{}} 57 c.Set(NOTICECTX, notice) 58 return ctx, notice 59 60 case nil: 61 default: 62 } 63 64 notice := &Notice{data: map[string]interface{}{}} 65 return ctx, notice 66 } 67 68 // 参数args: [key value]... 69 func PushNotice(ctx context.Context, args ...interface{}) { 70 ctx, notice := GetNoticeFromContext(ctx) 71 notice.Push(args...) 72 }