strslice.go 828 B

123456789101112131415161718192021222324252627282930
  1. package strslice // import "github.com/docker/docker/api/types/strslice"
  2. import "encoding/json"
  3. // StrSlice represents a string or an array of strings.
  4. // We need to override the json decoder to accept both options.
  5. type StrSlice []string
  6. // UnmarshalJSON decodes the byte slice whether it's a string or an array of
  7. // strings. This method is needed to implement json.Unmarshaler.
  8. func (e *StrSlice) UnmarshalJSON(b []byte) error {
  9. if len(b) == 0 {
  10. // With no input, we preserve the existing value by returning nil and
  11. // leaving the target alone. This allows defining default values for
  12. // the type.
  13. return nil
  14. }
  15. p := make([]string, 0, 1)
  16. if err := json.Unmarshal(b, &p); err != nil {
  17. var s string
  18. if err := json.Unmarshal(b, &s); err != nil {
  19. return err
  20. }
  21. p = append(p, s)
  22. }
  23. *e = p
  24. return nil
  25. }