github.com/ttys3/engine@v17.12.1-ce-rc2+incompatible/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 "strings" 7 ) 8 9 // VersionInfo is used to model UserAgent versions. 10 type VersionInfo struct { 11 Name string 12 Version string 13 } 14 15 func (vi *VersionInfo) isValid() bool { 16 const stopChars = " \t\r\n/" 17 name := vi.Name 18 vers := vi.Version 19 if len(name) == 0 || strings.ContainsAny(name, stopChars) { 20 return false 21 } 22 if len(vers) == 0 || strings.ContainsAny(vers, stopChars) { 23 return false 24 } 25 return true 26 } 27 28 // AppendVersions converts versions to a string and appends the string to the string base. 29 // 30 // Each VersionInfo will be converted to a string in the format of 31 // "product/version", where the "product" is get from the name field, while 32 // version is get from the version field. Several pieces of version information 33 // will be concatenated and separated by space. 34 // 35 // Example: 36 // AppendVersions("base", VersionInfo{"foo", "1.0"}, VersionInfo{"bar", "2.0"}) 37 // results in "base foo/1.0 bar/2.0". 38 func AppendVersions(base string, versions ...VersionInfo) string { 39 if len(versions) == 0 { 40 return base 41 } 42 43 verstrs := make([]string, 0, 1+len(versions)) 44 if len(base) > 0 { 45 verstrs = append(verstrs, base) 46 } 47 48 for _, v := range versions { 49 if !v.isValid() { 50 continue 51 } 52 verstrs = append(verstrs, v.Name+"/"+v.Version) 53 } 54 return strings.Join(verstrs, " ") 55 }