diff options
Diffstat (limited to 'server/cmd')
-rw-r--r-- | server/cmd/main.go | 44 |
1 files changed, 27 insertions, 17 deletions
diff --git a/server/cmd/main.go b/server/cmd/main.go index 3cd118d..f886e2b 100644 --- a/server/cmd/main.go +++ b/server/cmd/main.go @@ -1,11 +1,15 @@ package main import ( + "context" "encoding/json" + "fmt" "log" "net/http" + "os" "regexp" - "strconv" + + "github.com/jackc/pgx/v5/pgxpool" "git.huntm.net/wedding/server/guests" ) @@ -15,12 +19,18 @@ type guestHandler struct { } type guestStore interface { - Get() (map[int]guests.Guest, error) - Add(id int, guest guests.Guest) error - Update(id int, guest guests.Guest) error + Get() ([]guests.Guest, error) + Add(guest guests.Guest) error + Update(guest guests.Guest) error } var ( + user = os.Getenv("USER") + pass = os.Getenv("PASS") + host = "localhost" + port = "5432" + database = "postgres" + guestRe = regexp.MustCompile(`^/guests/*$`) guestIdRe = regexp.MustCompile(`^/guests/([0-9]+)$`) ) @@ -51,26 +61,26 @@ func (h *guestHandler) getGuests(w http.ResponseWriter, _ *http.Request) { func (h *guestHandler) createGuest(w http.ResponseWriter, r *http.Request) { var guest guests.Guest err := json.NewDecoder(r.Body).Decode(&guest) - defer r.Body.Close() if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } + defer r.Body.Close() - guests, err := h.store.Get() + guestSlice, err := h.store.Get() if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } - for _, g := range guests { + for _, g := range guestSlice { if g.Id == guest.Id { http.Error(w, "Id already exists", http.StatusBadRequest) return } } - err = h.store.Add(guest.Id, guest) + err = h.store.Add(guest) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return @@ -88,19 +98,13 @@ func (h *guestHandler) updateGuest(w http.ResponseWriter, r *http.Request) { var guest guests.Guest err := json.NewDecoder(r.Body).Decode(&guest) - defer r.Body.Close() if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } + defer r.Body.Close() - id, err := strconv.Atoi(matches[1]) - if err != nil { - http.Error(w, "Cannot convert string to integer", http.StatusBadRequest) - return - } - - err = h.store.Update(id, guest) + err = h.store.Update(guest) if err != nil { http.Error(w, "Guest not found", http.StatusBadRequest) return @@ -121,7 +125,13 @@ func (h *guestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } func main() { - store := guests.NewMemStore() + db, err := pgxpool.New(context.Background(), fmt.Sprintf("postgres://%s:%s@%s:%s/%s", user, pass, host, port, database)) + if err != nil { + log.Fatal(err) + } + defer db.Close() + + store := guests.NewMemStore(db) guestHandler := newGuestHandler(store) mux := http.NewServeMux() |