Routes returns the HTTP handler for container-related routes.
()
| 707 | |
| 708 | // Routes returns the HTTP handler for container-related routes. |
| 709 | func (api *API) Routes() http.Handler { |
| 710 | r := chi.NewRouter() |
| 711 | |
| 712 | ensureInitialUpdateDoneMW := func(next http.Handler) http.Handler { |
| 713 | return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { |
| 714 | select { |
| 715 | case <-api.ctx.Done(): |
| 716 | httpapi.Write(r.Context(), rw, http.StatusServiceUnavailable, codersdk.Response{ |
| 717 | Message: "API closed", |
| 718 | Detail: "The API is closed and cannot process requests.", |
| 719 | }) |
| 720 | return |
| 721 | case <-r.Context().Done(): |
| 722 | return |
| 723 | case <-api.initialUpdateDone: |
| 724 | // Initial update is done, we can start processing requests. |
| 725 | } |
| 726 | next.ServeHTTP(rw, r) |
| 727 | }) |
| 728 | } |
| 729 | |
| 730 | // For now, all endpoints require the initial update to be done. |
| 731 | // If we want to allow some endpoints to be available before |
| 732 | // the initial update, we can enable this per-route. |
| 733 | r.Use(ensureInitialUpdateDoneMW) |
| 734 | |
| 735 | r.Get("/", api.handleList) |
| 736 | r.Get("/watch", api.watchContainers) |
| 737 | // TODO(mafredri): Simplify this route as the previous /devcontainers |
| 738 | // /-route was dropped. We can drop the /devcontainers prefix here too. |
| 739 | r.Route("/devcontainers/{devcontainer}", func(r chi.Router) { |
| 740 | r.Post("/recreate", api.handleDevcontainerRecreate) |
| 741 | r.Delete("/", api.handleDevcontainerDelete) |
| 742 | }) |
| 743 | |
| 744 | return r |
| 745 | } |
| 746 | |
| 747 | // broadcastUpdatesLocked sends the current state to any listening clients. |
| 748 | // This method assumes that api.mu is held. |