collinenlucy.nl/server/controller.go

58 lines
1.1 KiB
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
err := json.NewDecoder(r.Body).Decode(&rsvp)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
_, err = rsvp.CreateRsvp(h.db)
fmt.Printf("%#v\n", rsvp)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if h.ntfy != nil {
SendRsvpNotification(h.ntfy, &rsvp)
}
w.WriteHeader(http.StatusAccepted)
default:
w.WriteHeader(http.StatusNotFound)
}
}