get.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package state
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "github.com/porter-dev/porter/api/server/shared/apierrors"
  7. "github.com/porter-dev/porter/api/types"
  8. "github.com/porter-dev/porter/internal/models"
  9. "github.com/porter-dev/porter/provisioner/integrations/storage"
  10. "github.com/porter-dev/porter/provisioner/server/config"
  11. ptypes "github.com/porter-dev/porter/provisioner/types"
  12. )
  13. type StateGetHandler struct {
  14. Config *config.Config
  15. }
  16. func NewStateGetHandler(
  17. config *config.Config,
  18. ) *StateGetHandler {
  19. return &StateGetHandler{
  20. Config: config,
  21. }
  22. }
  23. func (c *StateGetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  24. // read the infra from the attached scope
  25. infra, _ := r.Context().Value(types.InfraScope).(*models.Infra)
  26. fileBytes, err := c.Config.StorageManager.ReadFile(infra, ptypes.DefaultCurrentStateFile, true)
  27. if err != nil {
  28. // if the file does not exist yet, return a 404 status code
  29. if errors.Is(err, storage.FileDoesNotExist) {
  30. apierrors.HandleAPIError(c.Config.Logger, c.Config.Alerter, w, r, apierrors.NewErrPassThroughToClient(
  31. fmt.Errorf("current state file does not exist yet"),
  32. http.StatusNotFound,
  33. ), true)
  34. return
  35. }
  36. apierrors.HandleAPIError(c.Config.Logger, c.Config.Alerter, w, r, apierrors.NewErrInternal(err), true)
  37. return
  38. }
  39. if _, err = w.Write(fileBytes); err != nil {
  40. apierrors.HandleAPIError(c.Config.Logger, c.Config.Alerter, w, r, apierrors.NewErrInternal(err), true)
  41. return
  42. }
  43. }