collinenlucy.nl/server/controller.go

47 lines
925 B
Go
Raw Normal View History

2025-06-22 21:59:09 +02:00
package main
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"time"
)
type Handler struct {
db *sql.DB
ntfy *Ntfy
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Printf("%s - [%s] (%s) %s\n", time.Now().Format(time.RFC3339), r.RemoteAddr, r.Method, r.URL)
switch true {
case r.Method == "GET" && r.URL.Path == "/":
rsvps, err := GetRsvps(h.db)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s", err.Error())
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "%#v", rsvps)
case r.Method == "POST" && r.URL.Path == "/":
var rsvp Rsvp
json.NewDecoder(r.Body).Decode(&r)
_, err := rsvp.CreateRsvp(h.db)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
SendRsvpNotification(h.ntfy, &rsvp)
w.WriteHeader(http.StatusAccepted)
default:
w.WriteHeader(http.StatusNotFound)
}
}