Açıklama Yok
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

request_context.go 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. func GetContextTest() *RequestContext {
  46. return &RequestContext{
  47. TraceID: "test-TTraceID",
  48. TenantID: "test-TenantID",
  49. ServiceName: "test-ServiceName",
  50. InstanceName: "test-InstanceName",
  51. UserID: "test-UserID",
  52. Username: "test-Username",
  53. }
  54. }