Brak opisu
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 891B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. // Get 从请求获取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. if loggerCtx, ok := v.(RequestContext); ok {
  29. return &loggerCtx
  30. }
  31. }
  32. return &RequestContext{}
  33. }