api_version.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package auth
  2. import (
  3. "net/http"
  4. "strings"
  5. )
  6. // APIVersion represents a version of an API including its
  7. // type and version number.
  8. type APIVersion struct {
  9. // Type refers to the name of a specific API specification
  10. // such as "registry"
  11. Type string
  12. // Version is the version of the API specification implemented,
  13. // This may omit the revision number and only include
  14. // the major and minor version, such as "2.0"
  15. Version string
  16. }
  17. // String returns the string formatted API Version
  18. func (v APIVersion) String() string {
  19. return v.Type + "/" + v.Version
  20. }
  21. // APIVersions gets the API versions out of an HTTP response using the provided
  22. // version header as the key for the HTTP header.
  23. func APIVersions(resp *http.Response, versionHeader string) []APIVersion {
  24. versions := []APIVersion{}
  25. if versionHeader != "" {
  26. for _, supportedVersions := range resp.Header[http.CanonicalHeaderKey(versionHeader)] {
  27. for _, version := range strings.Fields(supportedVersions) {
  28. versions = append(versions, ParseAPIVersion(version))
  29. }
  30. }
  31. }
  32. return versions
  33. }
  34. // ParseAPIVersion parses an API version string into an APIVersion
  35. // Format (Expected, not enforced):
  36. // API version string = <API type> '/' <API version>
  37. // API type = [a-z][a-z0-9]*
  38. // API version = [0-9]+(\.[0-9]+)?
  39. // TODO(dmcgowan): Enforce format, add error condition, remove unknown type
  40. func ParseAPIVersion(versionStr string) APIVersion {
  41. idx := strings.IndexRune(versionStr, '/')
  42. if idx == -1 {
  43. return APIVersion{
  44. Type: "unknown",
  45. Version: versionStr,
  46. }
  47. }
  48. return APIVersion{
  49. Type: strings.ToLower(versionStr[:idx]),
  50. Version: versionStr[idx+1:],
  51. }
  52. }