github.com/khulnasoft-lab/khulnasoft@v26.0.1-0.20240328202558-330a6f959fe0+incompatible/api/server/server.go (about)

     1  package server // import "github.com/docker/docker/api/server"
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  
     7  	"github.com/containerd/log"
     8  	"github.com/docker/docker/api/server/httpstatus"
     9  	"github.com/docker/docker/api/server/httputils"
    10  	"github.com/docker/docker/api/server/middleware"
    11  	"github.com/docker/docker/api/server/router"
    12  	"github.com/docker/docker/api/server/router/debug"
    13  	"github.com/docker/docker/api/types"
    14  	"github.com/docker/docker/dockerversion"
    15  	"github.com/gorilla/mux"
    16  	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
    17  )
    18  
    19  // versionMatcher defines a variable matcher to be parsed by the router
    20  // when a request is about to be served.
    21  const versionMatcher = "/v{version:[0-9.]+}"
    22  
    23  // Server contains instance details for the server
    24  type Server struct {
    25  	middlewares []middleware.Middleware
    26  }
    27  
    28  // UseMiddleware appends a new middleware to the request chain.
    29  // This needs to be called before the API routes are configured.
    30  func (s *Server) UseMiddleware(m middleware.Middleware) {
    31  	s.middlewares = append(s.middlewares, m)
    32  }
    33  
    34  func (s *Server) makeHTTPHandler(handler httputils.APIFunc, operation string) http.HandlerFunc {
    35  	return otelhttp.NewHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    36  		// Define the context that we'll pass around to share info
    37  		// like the docker-request-id.
    38  		//
    39  		// The 'context' will be used for global data that should
    40  		// apply to all requests. Data that is specific to the
    41  		// immediate function being called should still be passed
    42  		// as 'args' on the function call.
    43  
    44  		// use intermediate variable to prevent "should not use basic type
    45  		// string as key in context.WithValue" golint errors
    46  		ctx := context.WithValue(r.Context(), dockerversion.UAStringKey{}, r.Header.Get("User-Agent"))
    47  
    48  		r = r.WithContext(ctx)
    49  		handlerFunc := s.handlerWithGlobalMiddlewares(handler)
    50  
    51  		vars := mux.Vars(r)
    52  		if vars == nil {
    53  			vars = make(map[string]string)
    54  		}
    55  
    56  		if err := handlerFunc(ctx, w, r, vars); err != nil {
    57  			statusCode := httpstatus.FromError(err)
    58  			if statusCode >= 500 {
    59  				log.G(ctx).Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err)
    60  			}
    61  			_ = httputils.WriteJSON(w, statusCode, &types.ErrorResponse{
    62  				Message: err.Error(),
    63  			})
    64  		}
    65  	}), operation).ServeHTTP
    66  }
    67  
    68  // CreateMux returns a new mux with all the routers registered.
    69  func (s *Server) CreateMux(routers ...router.Router) *mux.Router {
    70  	m := mux.NewRouter()
    71  
    72  	log.G(context.TODO()).Debug("Registering routers")
    73  	for _, apiRouter := range routers {
    74  		for _, r := range apiRouter.Routes() {
    75  			f := s.makeHTTPHandler(r.Handler(), r.Method()+" "+r.Path())
    76  
    77  			log.G(context.TODO()).Debugf("Registering %s, %s", r.Method(), r.Path())
    78  			m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f)
    79  			m.Path(r.Path()).Methods(r.Method()).Handler(f)
    80  		}
    81  	}
    82  
    83  	debugRouter := debug.NewRouter()
    84  	for _, r := range debugRouter.Routes() {
    85  		f := s.makeHTTPHandler(r.Handler(), r.Method()+" "+r.Path())
    86  		m.Path("/debug" + r.Path()).Handler(f)
    87  	}
    88  
    89  	notFoundHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    90  		_ = httputils.WriteJSON(w, http.StatusNotFound, &types.ErrorResponse{
    91  			Message: "page not found",
    92  		})
    93  	})
    94  
    95  	m.HandleFunc(versionMatcher+"/{path:.*}", notFoundHandler)
    96  	m.NotFoundHandler = notFoundHandler
    97  	m.MethodNotAllowedHandler = notFoundHandler
    98  
    99  	return m
   100  }