Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

Ability to use encoding.TextUnmarshaler #204

Closed
john8329 opened this issue Aug 22, 2020 · 1 comment · Fixed by #222
Closed

Ability to use encoding.TextUnmarshaler #204

john8329 opened this issue Aug 22, 2020 · 1 comment · Fixed by #222

Comments

@john8329
Copy link

john8329 commented Aug 22, 2020

I think it would be nice to have the library support the standard encoding.TextUnmarshaler interfaces, so when it's about to unmarshal a string into a field (which may be of its own type), it actually instantiates that type and calls its UnmarshalText() method.

This way the object we're unmarshalling to implicitly declares how it can decode data. A use case? UUIDs stored through arrays instead of strings.

An example implementation:

            fi := field.Interface()
_, canTextUnmarshal := fi.(encoding.TextUnmarshaler)
if canTextUnmarshal {
  t := field.Type().Elem()
  newValTyp := reflect.New(t)
  field.Set(newValTyp)

  unmarshaller, _ := field.Interface().(encoding.TextUnmarshaler)
  err := unmarshaller.UnmarshalText([]byte(v.(string)))
  if err != nil {
    panic(err)
  }
} else {
  newVal = reflect.ValueOf(v)
}

The standard go json decoder also implements this if I'm not mistaken.

Opinions?

@mitchellh
Copy link
Owner

I'd be open to a PR doing this. Thank you!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants