2016-02-24 13:17:43 -05:00
package middleware
import (
"fmt"
"net/http"
"runtime"
2016-09-15 13:30:07 -04:00
"github.com/docker/docker/api/errors"
2016-09-06 14:18:12 -04:00
"github.com/docker/docker/api/types/versions"
2016-02-24 13:17:43 -05:00
"golang.org/x/net/context"
)
2016-04-08 19:22:39 -04:00
// VersionMiddleware is a middleware that
// validates the client and server versions.
type VersionMiddleware struct {
2016-04-19 10:56:54 -04:00
serverVersion string
defaultVersion string
minVersion string
2016-04-08 19:22:39 -04:00
}
// NewVersionMiddleware creates a new VersionMiddleware
// with the default versions.
2016-04-19 10:56:54 -04:00
func NewVersionMiddleware ( s , d , m string ) VersionMiddleware {
2016-04-08 19:22:39 -04:00
return VersionMiddleware {
serverVersion : s ,
defaultVersion : d ,
minVersion : m ,
}
}
// WrapHandler returns a new handler function wrapping the previous one in the request chain.
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 {
return func ( ctx context . Context , w http . ResponseWriter , r * http . Request , vars map [ string ] string ) error {
2016-04-19 10:56:54 -04:00
apiVersion := vars [ "version" ]
2016-04-08 19:22:39 -04:00
if apiVersion == "" {
apiVersion = v . defaultVersion
2016-02-24 13:17:43 -05:00
}
2016-04-08 19:22:39 -04:00
2016-04-19 10:56:54 -04:00
if versions . GreaterThan ( apiVersion , v . defaultVersion ) {
2016-09-15 13:30:07 -04:00
return errors . NewBadRequestError ( fmt . Errorf ( "client is newer than server (client API version: %s, server API version: %s)" , apiVersion , v . defaultVersion ) )
2016-04-08 19:22:39 -04:00
}
2016-04-19 10:56:54 -04:00
if versions . LessThan ( apiVersion , v . minVersion ) {
2016-09-15 13:30:07 -04:00
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 ) )
2016-04-08 19:22:39 -04:00
}
header := fmt . Sprintf ( "Docker/%s (%s)" , v . serverVersion , runtime . GOOS )
w . Header ( ) . Set ( "Server" , header )
ctx = context . WithValue ( ctx , "api-version" , apiVersion )
return handler ( ctx , w , r , vars )
2016-02-24 13:17:43 -05:00
}
2016-04-08 19:22:39 -04:00
2016-02-24 13:17:43 -05:00
}