// createMux initializes the main router the server uses. func (s *Server) createMux() *mux.Router { m := mux.NewRouter() logrus.Debug("Registering routers") for _, apiRouter := range s.routers { for _, r := range apiRouter.Routes() { f := s.makeHTTPHandler(r.Handler()) logrus.Debugf("Registering %s, %s", r.Method(), r.Path()) m.Path(versionMatcher + r.Path()).Methods(r.Method()).Handler(f) m.Path(r.Path()).Methods(r.Method()).Handler(f) } } err := errors.NewRequestNotFoundError(fmt.Errorf("page not found")) notFoundHandler := httputils.MakeErrorHandler(err) m.HandleFunc(versionMatcher+"/{path:.*}", notFoundHandler) m.NotFoundHandler = notFoundHandler return m }
func (s *Server) makeHTTPHandler(handler httputils.APIFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // Define the context that we'll pass around to share info // like the docker-request-id. // // The 'context' will be used for global data that should // apply to all requests. Data that is specific to the // immediate function being called should still be passed // as 'args' on the function call. ctx := context.WithValue(context.Background(), httputils.UAStringKey, r.Header.Get("User-Agent")) handlerFunc := s.handlerWithGlobalMiddlewares(handler) vars := mux.Vars(r) if vars == nil { vars = make(map[string]string) } if err := handlerFunc(ctx, w, r, vars); err != nil { logrus.Errorf("Handler for %s %s returned error: %v", r.Method, r.URL.Path, err) httputils.MakeErrorHandler(err)(w, r) } } }