version.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/http"
  5. "runtime"
  6. "github.com/docker/docker/api/types/versions"
  7. "golang.org/x/net/context"
  8. )
  9. // VersionMiddleware is a middleware that
  10. // validates the client and server versions.
  11. type VersionMiddleware struct {
  12. serverVersion string
  13. defaultVersion string
  14. minVersion string
  15. }
  16. // NewVersionMiddleware creates a new VersionMiddleware
  17. // with the default versions.
  18. func NewVersionMiddleware(s, d, m string) VersionMiddleware {
  19. return VersionMiddleware{
  20. serverVersion: s,
  21. defaultVersion: d,
  22. minVersion: m,
  23. }
  24. }
  25. type versionUnsupportedError struct {
  26. version, minVersion, maxVersion string
  27. }
  28. func (e versionUnsupportedError) Error() string {
  29. if e.minVersion != "" {
  30. return fmt.Sprintf("client version %s is too old. Minimum supported API version is %s, please upgrade your client to a newer version", e.version, e.minVersion)
  31. }
  32. return fmt.Sprintf("client version %s is too new. Maximum supported API version is %s", e.version, e.maxVersion)
  33. }
  34. func (e versionUnsupportedError) InvalidParameter() {}
  35. // WrapHandler returns a new handler function wrapping the previous one in the request chain.
  36. func (v VersionMiddleware) WrapHandler(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  37. return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  38. apiVersion := vars["version"]
  39. if apiVersion == "" {
  40. apiVersion = v.defaultVersion
  41. }
  42. if versions.LessThan(apiVersion, v.minVersion) {
  43. return versionUnsupportedError{version: apiVersion, minVersion: v.minVersion}
  44. }
  45. if versions.GreaterThan(apiVersion, v.defaultVersion) {
  46. return versionUnsupportedError{version: apiVersion, maxVersion: v.defaultVersion}
  47. }
  48. header := fmt.Sprintf("Docker/%s (%s)", v.serverVersion, runtime.GOOS)
  49. w.Header().Set("Server", header)
  50. w.Header().Set("API-Version", v.defaultVersion)
  51. w.Header().Set("OSType", runtime.GOOS)
  52. // nolint: golint
  53. ctx = context.WithValue(ctx, "api-version", apiVersion)
  54. return handler(ctx, w, r, vars)
  55. }
  56. }