version.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 string
  27. }
  28. func (e versionUnsupportedError) Error() string {
  29. 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)
  30. }
  31. func (e versionUnsupportedError) InvalidParameter() {}
  32. // WrapHandler returns a new handler function wrapping the previous one in the request chain.
  33. 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 {
  34. return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  35. apiVersion := vars["version"]
  36. if apiVersion == "" {
  37. apiVersion = v.defaultVersion
  38. }
  39. if versions.LessThan(apiVersion, v.minVersion) {
  40. return versionUnsupportedError{apiVersion, v.minVersion}
  41. }
  42. header := fmt.Sprintf("Docker/%s (%s)", v.serverVersion, runtime.GOOS)
  43. w.Header().Set("Server", header)
  44. w.Header().Set("API-Version", v.defaultVersion)
  45. w.Header().Set("OSType", runtime.GOOS)
  46. // nolint: golint
  47. ctx = context.WithValue(ctx, "api-version", apiVersion)
  48. return handler(ctx, w, r, vars)
  49. }
  50. }