gctx.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. // Package gctx wraps context.Context and provides extra context features.
  7. package gctx
  8. import (
  9. "context"
  10. "github.com/gogf/gf/util/guid"
  11. )
  12. type (
  13. Ctx = context.Context // Ctx is short name alias for context.Context.
  14. StrKey string // StrKey is a type for warps basic type string as context key.
  15. )
  16. const (
  17. // CtxKey is custom tracing context key for context id.
  18. // The context id a unique string for certain context.
  19. CtxKey StrKey = "GoFrameCtxId"
  20. )
  21. // New creates and returns a context which contains context id.
  22. func New() context.Context {
  23. return WithCtx(context.Background())
  24. }
  25. // WithCtx creates and returns a context containing context id upon given parent context `ctx`.
  26. func WithCtx(ctx context.Context) context.Context {
  27. return WithPrefix(ctx, "")
  28. }
  29. // WithPrefix creates and returns a context containing context id upon given parent context `ctx`.
  30. // The generated context id has custom prefix string specified by parameter `prefix`.
  31. func WithPrefix(ctx context.Context, prefix string) context.Context {
  32. return WithValue(ctx, prefix+getUniqueID())
  33. }
  34. // WithValue creates and returns a context containing context id upon given parent context `ctx`.
  35. // The generated context id value is specified by parameter `value`.
  36. func WithValue(ctx context.Context, value string) context.Context {
  37. if value == "" {
  38. return New()
  39. }
  40. return context.WithValue(ctx, CtxKey, value)
  41. }
  42. // Value retrieves and returns the context id from context.
  43. func Value(ctx context.Context) string {
  44. s, _ := ctx.Value(CtxKey).(string)
  45. return s
  46. }
  47. // getUniqueID produces a global unique string.
  48. func getUniqueID() string {
  49. return guid.S()
  50. }