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