gctx.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. }
  41. // New creates and returns a context which contains context id.
  42. func New() context.Context {
  43. return WithCtx(context.Background())
  44. }
  45. // WithCtx creates and returns a context containing context id upon given parent context `ctx`.
  46. func WithCtx(ctx context.Context) context.Context {
  47. if CtxId(ctx) != "" {
  48. return ctx
  49. }
  50. if gtrace.IsUsingDefaultProvider() {
  51. var span *gtrace.Span
  52. ctx, span = gtrace.NewSpan(ctx, "gctx.WithCtx")
  53. defer span.End()
  54. }
  55. return ctx
  56. }
  57. // CtxId retrieves and returns the context id from context.
  58. func CtxId(ctx context.Context) string {
  59. return gtrace.GetTraceID(ctx)
  60. }
  61. // SetInitCtx sets custom initialization context.
  62. // Note that this function cannot be called in multiple goroutines.
  63. func SetInitCtx(ctx context.Context) {
  64. initCtx = ctx
  65. }
  66. // GetInitCtx returns the initialization context.
  67. // Initialization context is used in `main` or `init` functions.
  68. func GetInitCtx() context.Context {
  69. return initCtx
  70. }