설명 없음
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.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package ctx
  2. import (
  3. "context"
  4. "net/http"
  5. )
  6. // UserContext 用户上下文
  7. type RequestContext struct {
  8. TraceID string `json:"trace_id"`
  9. ServiceName string `json:"service_name"`
  10. InstanceName string `json:"instance_name"`
  11. TenantID string `json:"tenant_id"`
  12. UserID string `json:"user_id"`
  13. ProjectID string `json:"project_id"`
  14. }
  15. // 内部key,不会和其他包冲突
  16. type ctxKey struct{}
  17. var loggerKey = ctxKey{}
  18. // Save RequestContext
  19. func SaveContext(r *http.Request, requestContext *RequestContext) *http.Request {
  20. ctx := context.WithValue(r.Context(), loggerKey, requestContext)
  21. return r.WithContext(ctx)
  22. }
  23. // GetContext 从请求获取RequestContext
  24. func GetContext(r *http.Request) *RequestContext {
  25. if r == nil {
  26. return &RequestContext{}
  27. }
  28. if v := r.Context().Value(loggerKey); v != nil {
  29. // 修正:类型断言为 *RequestContext
  30. if loggerCtx, ok := v.(*RequestContext); ok {
  31. return loggerCtx
  32. }
  33. }
  34. return &RequestContext{}
  35. }
  36. func GetContextTest() *RequestContext {
  37. return &RequestContext{
  38. TraceID: "test-TTraceID",
  39. TenantID: "test-TenantID",
  40. ServiceName: "test-ServiceName",
  41. InstanceName: "test-InstanceName",
  42. UserID: "test-UserID",
  43. }
  44. }