github.com/michael-k/docker@v1.7.0-rc2/pkg/useragent/useragent.go (about)

     1  // Package useragent provides helper functions to pack
     2  // version information into a single User-Agent header.
     3  package useragent
     4  
     5  import (
     6  	"errors"
     7  	"strings"
     8  )
     9  
    10  var (
    11  	ErrNilRequest = errors.New("request cannot be nil")
    12  )
    13  
    14  // VersionInfo is used to model UserAgent versions.
    15  type VersionInfo struct {
    16  	Name    string
    17  	Version string
    18  }
    19  
    20  func (vi *VersionInfo) isValid() bool {
    21  	const stopChars = " \t\r\n/"
    22  	name := vi.Name
    23  	vers := vi.Version
    24  	if len(name) == 0 || strings.ContainsAny(name, stopChars) {
    25  		return false
    26  	}
    27  	if len(vers) == 0 || strings.ContainsAny(vers, stopChars) {
    28  		return false
    29  	}
    30  	return true
    31  }
    32  
    33  // Convert versions to a string and append the string to the string base.
    34  //
    35  // Each VersionInfo will be converted to a string in the format of
    36  // "product/version", where the "product" is get from the name field, while
    37  // version is get from the version field. Several pieces of verson information
    38  // will be concatinated and separated by space.
    39  //
    40  // Example:
    41  // AppendVersions("base", VersionInfo{"foo", "1.0"}, VersionInfo{"bar", "2.0"})
    42  // results in "base foo/1.0 bar/2.0".
    43  func AppendVersions(base string, versions ...VersionInfo) string {
    44  	if len(versions) == 0 {
    45  		return base
    46  	}
    47  
    48  	verstrs := make([]string, 0, 1+len(versions))
    49  	if len(base) > 0 {
    50  		verstrs = append(verstrs, base)
    51  	}
    52  
    53  	for _, v := range versions {
    54  		if !v.isValid() {
    55  			continue
    56  		}
    57  		verstrs = append(verstrs, v.Name+"/"+v.Version)
    58  	}
    59  	return strings.Join(verstrs, " ")
    60  }