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