version.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/http"
  5. "runtime"
  6. "github.com/docker/docker/api/server/httputils"
  7. "github.com/docker/docker/pkg/version"
  8. "golang.org/x/net/context"
  9. )
  10. type badRequestError struct {
  11. error
  12. }
  13. func (badRequestError) HTTPErrorStatusCode() int {
  14. return http.StatusBadRequest
  15. }
  16. // NewVersionMiddleware creates a new Version middleware.
  17. func NewVersionMiddleware(versionCheck string, defaultVersion, minVersion version.Version) Middleware {
  18. serverVersion := version.Version(versionCheck)
  19. return func(handler httputils.APIFunc) httputils.APIFunc {
  20. return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  21. apiVersion := version.Version(vars["version"])
  22. if apiVersion == "" {
  23. apiVersion = defaultVersion
  24. }
  25. if apiVersion.GreaterThan(defaultVersion) {
  26. return badRequestError{fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", apiVersion, defaultVersion)}
  27. }
  28. if apiVersion.LessThan(minVersion) {
  29. return badRequestError{fmt.Errorf("client version %s is too old. Minimum supported API version is %s, please upgrade your client to a newer version", apiVersion, minVersion)}
  30. }
  31. header := fmt.Sprintf("Docker/%s (%s)", serverVersion, runtime.GOOS)
  32. w.Header().Set("Server", header)
  33. ctx = context.WithValue(ctx, httputils.APIVersionKey, apiVersion)
  34. return handler(ctx, w, r, vars)
  35. }
  36. }
  37. }