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