controller

This commit is contained in:
Bronku 2025-01-29 10:26:36 +01:00
parent 28a3ca3bb4
commit 8c3611e859
6 changed files with 78 additions and 30 deletions

46
controller/controller.go Normal file
View file

@ -0,0 +1,46 @@
package controller
import (
"fmt"
"html/template"
"io/fs"
"net/http"
)
type Controller struct {
tmpl map[string]*template.Template
http.Handler
}
// #todo: load all automatically
func (c *Controller) LoadTemplates(fs fs.FS) {
c.tmpl = make(map[string]*template.Template)
c.tmpl["order/confirmation.html"], _ = template.ParseFS(fs, "templates/order/confirmation.html")
c.tmpl["new_order.html"], _ = template.ParseFS(fs, "templates/new_order.html")
}
func (c *Controller) LoadRouter(pub fs.FS) {
serveMux := http.NewServeMux()
serveMux.Handle("GET /", http.FileServerFS(unwrap(fs.Sub(pub, "public"))))
serveMux.HandleFunc("POST /", c.HandlePost)
serveMux.HandleFunc("GET /new_order.html", c.HandleGet)
c.Handler = serveMux
}
func (c *Controller) HandlePost(w http.ResponseWriter, r *http.Request) {
fmt.Println("received Post request: ", r)
err := r.ParseForm()
if err != nil {
_ = c.tmpl["order/confirmation.html"].Execute(w, struct{ Status any }{Status: err})
}
w.WriteHeader(http.StatusAccepted)
fmt.Println(r.Form)
_ = c.tmpl["order/confirmation.html"].Execute(w, struct{ Status any }{Status: r.Form})
}
func (c *Controller) HandleGet(w http.ResponseWriter, r *http.Request) {
fmt.Println("received Get request: ", r)
_ = c.tmpl["new_order.html"].Execute(w, nil)
}

8
controller/util.go Normal file
View file

@ -0,0 +1,8 @@
package controller
func unwrap[T any](output T, err error) T {
if err != nil {
panic(err)
}
return output
}