github.com/portworx/docker@v1.12.1/api/server/middleware/version.go (about)

     1  package middleware
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"runtime"
     7  
     8  	"github.com/docker/engine-api/types/versions"
     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  string
    24  	defaultVersion string
    25  	minVersion     string
    26  }
    27  
    28  // NewVersionMiddleware creates a new VersionMiddleware
    29  // with the default versions.
    30  func NewVersionMiddleware(s, d, m string) 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 := vars["version"]
    42  		if apiVersion == "" {
    43  			apiVersion = v.defaultVersion
    44  		}
    45  
    46  		if versions.GreaterThan(apiVersion, 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 versions.LessThan(apiVersion, 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  }