github.com/hayajo/docker@v1.9.1/pkg/stringutils/strslice.go (about)

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