github.com/gogf/gf@v1.16.9/os/gctx/gctx.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  // Package gctx wraps context.Context and provides extra context features.
     8  package gctx
     9  
    10  import (
    11  	"context"
    12  	"github.com/gogf/gf/util/guid"
    13  )
    14  
    15  type (
    16  	Ctx    = context.Context // Ctx is short name alias for context.Context.
    17  	StrKey string            // StrKey is a type for warps basic type string as context key.
    18  )
    19  
    20  const (
    21  	// CtxKey is custom tracing context key for context id.
    22  	// The context id a unique string for certain context.
    23  	CtxKey StrKey = "GoFrameCtxId"
    24  )
    25  
    26  // New creates and returns a context which contains context id.
    27  func New() context.Context {
    28  	return WithCtx(context.Background())
    29  }
    30  
    31  // WithCtx creates and returns a context containing context id upon given parent context `ctx`.
    32  func WithCtx(ctx context.Context) context.Context {
    33  	return WithPrefix(ctx, "")
    34  }
    35  
    36  // WithPrefix creates and returns a context containing context id upon given parent context `ctx`.
    37  // The generated context id has custom prefix string specified by parameter `prefix`.
    38  func WithPrefix(ctx context.Context, prefix string) context.Context {
    39  	return WithValue(ctx, prefix+getUniqueID())
    40  }
    41  
    42  // WithValue creates and returns a context containing context id upon given parent context `ctx`.
    43  // The generated context id value is specified by parameter `value`.
    44  func WithValue(ctx context.Context, value string) context.Context {
    45  	if value == "" {
    46  		return New()
    47  	}
    48  	return context.WithValue(ctx, CtxKey, value)
    49  }
    50  
    51  // Value retrieves and returns the context id from context.
    52  func Value(ctx context.Context) string {
    53  	s, _ := ctx.Value(CtxKey).(string)
    54  	return s
    55  }
    56  
    57  // getUniqueID produces a global unique string.
    58  func getUniqueID() string {
    59  	return guid.S()
    60  }