mapiter.go 939 B

123456789101112131415161718192021222324252627282930313233343536
  1. package iter
  2. import (
  3. "context"
  4. "github.com/lestrrat-go/iter/mapiter"
  5. "github.com/pkg/errors"
  6. )
  7. // MapVisitor is a specialized visitor for our purposes.
  8. // Whereas mapiter.Visitor supports any type of key, this
  9. // visitor assumes the key is a string
  10. type MapVisitor interface {
  11. Visit(string, interface{}) error
  12. }
  13. type MapVisitorFunc func(string, interface{}) error
  14. func (fn MapVisitorFunc) Visit(s string, v interface{}) error {
  15. return fn(s, v)
  16. }
  17. func WalkMap(ctx context.Context, src mapiter.Source, visitor MapVisitor) error {
  18. return mapiter.Walk(ctx, src, mapiter.VisitorFunc(func(k, v interface{}) error {
  19. //nolint:forcetypeassert
  20. return visitor.Visit(k.(string), v)
  21. }))
  22. }
  23. func AsMap(ctx context.Context, src mapiter.Source) (map[string]interface{}, error) {
  24. var m map[string]interface{}
  25. if err := mapiter.AsMap(ctx, src, &m); err != nil {
  26. return nil, errors.Wrap(err, `mapiter.AsMap failed`)
  27. }
  28. return m, nil
  29. }