unmarshaler.go 494 B

123456789101112131415161718192021222324252627
  1. package contextx
  2. import (
  3. "context"
  4. "github.com/tal-tech/go-zero/core/mapping"
  5. )
  6. const contextTagKey = "ctx"
  7. var unmarshaler = mapping.NewUnmarshaler(contextTagKey)
  8. type contextValuer struct {
  9. context.Context
  10. }
  11. func (cv contextValuer) Value(key string) (interface{}, bool) {
  12. v := cv.Context.Value(key)
  13. return v, v != nil
  14. }
  15. // For unmarshals ctx into v.
  16. func For(ctx context.Context, v interface{}) error {
  17. return unmarshaler.UnmarshalValuer(contextValuer{
  18. Context: ctx,
  19. }, v)
  20. }