strslice.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package strslice
  2. import (
  3. "encoding/json"
  4. "strings"
  5. )
  6. // StrSlice represents a string or an array of strings.
  7. // We need to override the json decoder to accept both options.
  8. type StrSlice struct {
  9. parts []string
  10. }
  11. // MarshalJSON Marshals (or serializes) the StrSlice into the json format.
  12. // This method is needed to implement json.Marshaller.
  13. func (e *StrSlice) MarshalJSON() ([]byte, error) {
  14. if e == nil {
  15. return []byte{}, nil
  16. }
  17. return json.Marshal(e.Slice())
  18. }
  19. // UnmarshalJSON decodes the byte slice whether it's a string or an array of strings.
  20. // This method is needed to implement json.Unmarshaler.
  21. func (e *StrSlice) UnmarshalJSON(b []byte) error {
  22. if len(b) == 0 {
  23. return nil
  24. }
  25. p := make([]string, 0, 1)
  26. if err := json.Unmarshal(b, &p); err != nil {
  27. var s string
  28. if err := json.Unmarshal(b, &s); err != nil {
  29. return err
  30. }
  31. p = append(p, s)
  32. }
  33. e.parts = p
  34. return nil
  35. }
  36. // Len returns the number of parts of the StrSlice.
  37. func (e *StrSlice) Len() int {
  38. if e == nil {
  39. return 0
  40. }
  41. return len(e.parts)
  42. }
  43. // Slice gets the parts of the StrSlice as a Slice of string.
  44. func (e *StrSlice) Slice() []string {
  45. if e == nil {
  46. return nil
  47. }
  48. return e.parts
  49. }
  50. // ToString gets space separated string of all the parts.
  51. func (e *StrSlice) ToString() string {
  52. s := e.Slice()
  53. if s == nil {
  54. return ""
  55. }
  56. return strings.Join(s, " ")
  57. }
  58. // New creates an StrSlice based on the specified parts (as strings).
  59. func New(parts ...string) *StrSlice {
  60. return &StrSlice{parts}
  61. }