Ingen beskrivning
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.

RequestContext.go 945B

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. }
  14. // 内部key,不会和其他包冲突
  15. type ctxKey struct{}
  16. var loggerKey = ctxKey{}
  17. // Save RequestContext
  18. func SaveContext(r *http.Request, requestContext *RequestContext) *http.Request {
  19. ctx := context.WithValue(r.Context(), loggerKey, requestContext)
  20. return r.WithContext(ctx)
  21. }
  22. // GetContext 从请求获取RequestContext
  23. func GetContext(r *http.Request) *RequestContext {
  24. if r == nil {
  25. return &RequestContext{}
  26. }
  27. if v := r.Context().Value(loggerKey); v != nil {
  28. // 修正:类型断言为 *RequestContext
  29. if loggerCtx, ok := v.(*RequestContext); ok {
  30. return loggerCtx
  31. }
  32. }
  33. return &RequestContext{}
  34. }