version.go 1.6 KB

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