probo/cmd/serve/controller.go

65 lines
1.2 KiB
Go
Raw Normal View History

package serve
import (
"bytes"
"html/template"
"net/http"
"git.andreafazzi.eu/andrea/probo/pkg/store/file"
)
type Controller struct {
handlerFunc http.HandlerFunc
sStore *file.SessionFileStore
rStore *file.ResponseFileStore
template *template.Template
}
func NewController(sStore *file.SessionFileStore, rStore *file.ResponseFileStore) *Controller {
return &Controller{
sStore: sStore,
rStore: rStore,
}
}
func (c *Controller) WithHandlerFunc(f func(c *Controller, w http.ResponseWriter, r *http.Request)) *Controller {
hf := func(w http.ResponseWriter, r *http.Request) {
f(c, w, r)
}
c.handlerFunc = hf
return c
}
func (c *Controller) WithTemplates(paths ...string) *Controller {
tmpl, err := template.ParseFiles(paths...)
if err != nil {
panic(err)
}
c.template = tmpl
return c
}
func (c *Controller) ExecuteTemplate(w http.ResponseWriter, data any) error {
var buf bytes.Buffer
err := c.template.Execute(&buf, data)
if err != nil {
return err
}
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
buf.WriteTo(w)
return nil
}
func (c *Controller) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c.handlerFunc.ServeHTTP(w, r)
}