説明なし
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

request_context.go 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package ctx
  2. import (
  3. "context"
  4. "net/http"
  5. )
  6. // UserContext 用户上下文
  7. type RequestContext struct {
  8. //StdCtx context.Context // 新增:标准上下文
  9. TraceID string `json:"trace_id"`
  10. ServiceName string `json:"service_name"`
  11. InstanceName string `json:"instance_name"`
  12. TenantID string `json:"tenant_id"`
  13. UserID string `json:"user_id"`
  14. ProjectID string `json:"project_id"`
  15. Username string `json:"username"`
  16. }
  17. // 内部key,不会和其他包冲突
  18. type ctxKey struct{}
  19. var loggerKey = ctxKey{}
  20. // // GetStdContext 获取标准上下文(方便使用)
  21. // func (rc *RequestContext) GetStdContext() context.Context {
  22. // if rc.StdCtx == nil {
  23. // return context.Background()
  24. // }
  25. // return rc.StdCtx
  26. // }
  27. // Save RequestContext
  28. func SaveContext(r *http.Request, requestContext *RequestContext) *http.Request {
  29. ctx := context.WithValue(r.Context(), loggerKey, requestContext)
  30. return r.WithContext(ctx)
  31. }
  32. // GetContext 从请求获取RequestContext
  33. func GetContext(r *http.Request) *RequestContext {
  34. if r == nil {
  35. return &RequestContext{}
  36. }
  37. if v := r.Context().Value(loggerKey); v != nil {
  38. // 修正:类型断言为 *RequestContext
  39. if loggerCtx, ok := v.(*RequestContext); ok {
  40. return loggerCtx
  41. }
  42. }
  43. return &RequestContext{}
  44. }
  45. // FromContext 从 context.Context 中提取 RequestContext
  46. func FromContext(ctx context.Context) *RequestContext {
  47. if ctx == nil {
  48. return &RequestContext{}
  49. }
  50. if v := ctx.Value(loggerKey); v != nil {
  51. if reqCtx, ok := v.(*RequestContext); ok {
  52. return reqCtx
  53. }
  54. }
  55. return &RequestContext{}
  56. }
  57. func GetContextTest() *RequestContext {
  58. return &RequestContext{
  59. TraceID: "test-TTraceID",
  60. TenantID: "test-TenantID",
  61. ServiceName: "test-ServiceName",
  62. InstanceName: "test-InstanceName",
  63. UserID: "test-UserID",
  64. Username: "test-Username",
  65. ProjectID: "test-ProjectID",
  66. }
  67. }