version.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/http"
  5. "runtime"
  6. "github.com/docker/engine-api/types/versions"
  7. "golang.org/x/net/context"
  8. )
  9. type badRequestError struct {
  10. error
  11. }
  12. func (badRequestError) HTTPErrorStatusCode() int {
  13. return http.StatusBadRequest
  14. }
  15. // VersionMiddleware is a middleware that
  16. // validates the client and server versions.
  17. type VersionMiddleware struct {
  18. serverVersion string
  19. defaultVersion string
  20. minVersion string
  21. }
  22. // NewVersionMiddleware creates a new VersionMiddleware
  23. // with the default versions.
  24. func NewVersionMiddleware(s, d, m string) VersionMiddleware {
  25. return VersionMiddleware{
  26. serverVersion: s,
  27. defaultVersion: d,
  28. minVersion: m,
  29. }
  30. }
  31. // WrapHandler returns a new handler function wrapping the previous one in the request chain.
  32. 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 {
  33. return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  34. apiVersion := vars["version"]
  35. if apiVersion == "" {
  36. apiVersion = v.defaultVersion
  37. }
  38. if versions.GreaterThan(apiVersion, v.defaultVersion) {
  39. return badRequestError{fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", apiVersion, v.defaultVersion)}
  40. }
  41. if versions.LessThan(apiVersion, v.minVersion) {
  42. 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, v.minVersion)}
  43. }
  44. header := fmt.Sprintf("Docker/%s (%s)", v.serverVersion, runtime.GOOS)
  45. w.Header().Set("Server", header)
  46. ctx = context.WithValue(ctx, "api-version", apiVersion)
  47. return handler(ctx, w, r, vars)
  48. }
  49. }