gctx.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. "os"
  11. "strings"
  12. "go.opentelemetry.io/otel"
  13. "go.opentelemetry.io/otel/propagation"
  14. "github.com/gogf/gf/v2/net/gtrace"
  15. )
  16. type (
  17. Ctx = context.Context // Ctx is short name alias for context.Context.
  18. StrKey string // StrKey is a type for warps basic type string as context key.
  19. )
  20. var (
  21. // initCtx is the context initialized from process environment.
  22. initCtx context.Context
  23. )
  24. func init() {
  25. // All environment key-value pairs.
  26. m := make(map[string]string)
  27. i := 0
  28. for _, s := range os.Environ() {
  29. i = strings.IndexByte(s, '=')
  30. if i == -1 {
  31. continue
  32. }
  33. m[s[0:i]] = s[i+1:]
  34. }
  35. // OpenTelemetry from environments.
  36. initCtx = otel.GetTextMapPropagator().Extract(
  37. context.Background(),
  38. propagation.MapCarrier(m),
  39. )
  40. initCtx = WithCtx(initCtx)
  41. }
  42. // New creates and returns a context which contains context id.
  43. func New() context.Context {
  44. return WithCtx(context.Background())
  45. }
  46. // WithCtx creates and returns a context containing context id upon given parent context `ctx`.
  47. func WithCtx(ctx context.Context) context.Context {
  48. if CtxId(ctx) != "" {
  49. return ctx
  50. }
  51. var span *gtrace.Span
  52. ctx, span = gtrace.NewSpan(ctx, "gctx.WithCtx")
  53. defer span.End()
  54. return ctx
  55. }
  56. // CtxId retrieves and returns the context id from context.
  57. func CtxId(ctx context.Context) string {
  58. return gtrace.GetTraceID(ctx)
  59. }
  60. // SetInitCtx sets custom initialization context.
  61. // Note that this function cannot be called in multiple goroutines.
  62. func SetInitCtx(ctx context.Context) {
  63. initCtx = ctx
  64. }
  65. // GetInitCtx returns the initialization context.
  66. // Initialization context is used in `main` or `init` functions.
  67. func GetInitCtx() context.Context {
  68. return initCtx
  69. }