types.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package authority
  2. import (
  3. "encoding/json"
  4. "github.com/pkg/errors"
  5. )
  6. // multiString represents a type that can be encoded/decoded in JSON as a single
  7. // string or an array of strings.
  8. type multiString []string
  9. // First returns the first element of a multiString. It will return an empty
  10. // string if the multistring is empty.
  11. func (s multiString) First() string {
  12. if len(s) > 0 {
  13. return s[0]
  14. }
  15. return ""
  16. }
  17. // HasEmpties returns `true` if any string in the array is empty.
  18. func (s multiString) HasEmpties() bool {
  19. if len(s) == 0 {
  20. return true
  21. }
  22. for _, ss := range s {
  23. if len(ss) == 0 {
  24. return true
  25. }
  26. }
  27. return false
  28. }
  29. // MarshalJSON marshals the multistring as a string or a slice of strings . With
  30. // 0 elements it will return the empty string, with 1 element a regular string,
  31. // otherwise a slice of strings.
  32. func (s multiString) MarshalJSON() ([]byte, error) {
  33. switch len(s) {
  34. case 0:
  35. return []byte(`""`), nil
  36. case 1:
  37. return json.Marshal(s[0])
  38. default:
  39. return json.Marshal([]string(s))
  40. }
  41. }
  42. // UnmarshalJSON parses a string or a slice and sets it to the multiString.
  43. func (s *multiString) UnmarshalJSON(data []byte) error {
  44. if s == nil {
  45. return errors.New("multiString cannot be nil")
  46. }
  47. if len(data) == 0 {
  48. *s = nil
  49. return nil
  50. }
  51. // Parse string
  52. if data[0] == '"' {
  53. var str string
  54. if err := json.Unmarshal(data, &str); err != nil {
  55. return errors.Wrapf(err, "error unmarshalling %s", data)
  56. }
  57. *s = []string{str}
  58. return nil
  59. }
  60. // Parse array
  61. var ss []string
  62. if err := json.Unmarshal(data, &ss); err != nil {
  63. return errors.Wrapf(err, "error unmarshalling %s", data)
  64. }
  65. *s = ss
  66. return nil
  67. }