collinenlucy.nl/server/controller.go

86 lines
1.9 KiB
Go
Raw Normal View History

2025-06-30 12:37:33 +02:00
package main
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"os"
2025-06-30 12:37:33 +02:00
"time"
)
type Handler struct {
db *sql.DB
ntfy *Ntfy
}
func getStaticFile(relPath string, contentType string, w http.ResponseWriter) {
file, err := os.ReadFile(relPath)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "%s", err.Error())
return
}
w.Header().Add("Content-Type", contentType)
w.WriteHeader(http.StatusOK)
fmt.Printf("%s\n", w.Header().Get("Content-Type"))
w.Write(file)
}
2025-06-30 12:37:33 +02:00
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 == "/":
getStaticFile("../client/index.html", "text/html", w)
case r.Method == "GET" && r.URL.Path == "/rsvp":
getStaticFile("../client/rsvp.html", "text/html", w)
case r.Method == "GET" && r.URL.Path == "/index.js":
getStaticFile("../client/index.js", "text/javascript", w)
case r.Method == "GET" && r.URL.Path == "/style.css":
getStaticFile("../client/style.css", "text/css", w)
case r.Method == "GET" && r.URL.Path == "/api/rsvps":
2025-06-30 12:37:33 +02:00
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 == "/api/rsvps":
2025-06-30 12:37:33 +02:00
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)
}
}