github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/log/tapper/user_ctx.go (about)

     1  package tapper
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/gin-gonic/gin"
     7  )
     8  
     9  type UserContext struct {
    10  	LogUnit *LogUnits
    11  	GinCtx  context.Context
    12  	Error   error
    13  }
    14  
    15  type options struct {
    16  	UrlPath string
    17  	GinCtx  context.Context
    18  	Error   error
    19  }
    20  
    21  type Option func(*options)
    22  
    23  func WithGinCtx(ctx context.Context) Option {
    24  	return func(opt *options) {
    25  		opt.GinCtx = ctx
    26  	}
    27  }
    28  
    29  func WithUrlPath(urlPath string) Option {
    30  	return func(opt *options) {
    31  		opt.UrlPath = urlPath
    32  	}
    33  }
    34  
    35  func WithError(err error) Option {
    36  	return func(opt *options) {
    37  		opt.Error = err
    38  	}
    39  }
    40  
    41  func NewUserContext(opts ...Option) *UserContext {
    42  	logUnit := &LogUnits{}
    43  	o := &options{}
    44  	for _, opt := range opts {
    45  		opt(o)
    46  	}
    47  	logUnit.SetBeginTime()
    48  	logUnit.SetCmd(o.UrlPath)
    49  	return &UserContext{LogUnit: logUnit, GinCtx: o.GinCtx}
    50  }
    51  
    52  func (this *UserContext) SetErr(err error) {
    53  	this.LogUnit.AddLogUnit("err_info", err.Error())
    54  }
    55  
    56  func CtxTransfer(ctx context.Context, key string) *UserContext {
    57  	ginCtx, ok := ctx.(*gin.Context)
    58  	if !ok {
    59  		return NewUserContext(WithGinCtx(ctx))
    60  	}
    61  	l, ok := ginCtx.Get(key)
    62  	if !ok {
    63  		return NewUserContext(WithGinCtx(ctx))
    64  	}
    65  	userCtx, ok := l.(*UserContext)
    66  	if !ok {
    67  		return NewUserContext(WithGinCtx(ctx))
    68  	}
    69  	return userCtx
    70  }
    71  
    72  // gin.Context 属于对象池,因此在异步执行时,需要拷贝一个再使用.注:在多个goroutine中,应使用线程安全的AddLogUnit方法
    73  func (this *UserContext) Clone() *UserContext {
    74  	if this == nil {
    75  		return nil
    76  	}
    77  	q := &UserContext{}
    78  	if ginCtx, ok := this.GinCtx.(*gin.Context); ok {
    79  		q.GinCtx = ginCtx.Copy()
    80  	} else {
    81  		q.GinCtx = &gin.Context{}
    82  	}
    83  	q.LogUnit = this.LogUnit
    84  
    85  	return q
    86  }