From 36e3d473f2126e920061218996cfa5cfecade7d6 Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Mon, 30 Dec 2024 23:07:00 +0100 Subject: chore(tfstated): refactor backend code to a dedicated package --- pkg/backend/post.go | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 pkg/backend/post.go (limited to 'pkg/backend/post.go') diff --git a/pkg/backend/post.go b/pkg/backend/post.go new file mode 100644 index 0000000..8271022 --- /dev/null +++ b/pkg/backend/post.go @@ -0,0 +1,40 @@ +package backend + +import ( + "fmt" + "io" + "net/http" + + "git.adyxax.org/adyxax/tfstated/pkg/database" + "git.adyxax.org/adyxax/tfstated/pkg/helpers" + "git.adyxax.org/adyxax/tfstated/pkg/model" +) + +func handlePost(db *database.DB) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/" { + helpers.ErrorResponse(w, http.StatusBadRequest, + fmt.Errorf("no state path provided, cannot POST /"), + ) + return + } + + id := r.URL.Query().Get("ID") + + data, err := io.ReadAll(r.Body) + if err != nil || len(data) == 0 { + helpers.ErrorResponse(w, http.StatusBadRequest, err) + return + } + account := r.Context().Value(model.AccountContextKey{}).(*model.Account) + if idMismatch, err := db.SetState(r.URL.Path, account.Id, data, id); err != nil { + if idMismatch { + helpers.ErrorResponse(w, http.StatusConflict, err) + } else { + helpers.ErrorResponse(w, http.StatusInternalServerError, err) + } + } else { + w.WriteHeader(http.StatusOK) + } + }) +} -- cgit v1.2.3