Create handler type

This commit is contained in:
Brandon Dyck 2020-03-31 23:31:30 -06:00
parent da4cbc4c50
commit d07d5cac31

View File

@ -33,6 +33,59 @@ const (
var store *henwen.Store var store *henwen.Store
type handler struct {
mux *http.ServeMux
}
func NewHandler() http.Handler {
h := &handler{
mux: http.NewServeMux(),
}
h.mux.HandleFunc(pathRoot, h.handleRoot)
h.mux.HandleFunc(pathCreate, h.handleCreate)
h.mux.HandleFunc(pathDoCreate, h.handleDoCreate)
h.mux.HandleFunc(pathAdmin, h.handleAdmin)
return h
}
func (h *handler) handleRoot(w http.ResponseWriter, r *http.Request) {
_ = writePage(w, pageRoot())
}
func (h *handler) handleCreate(w http.ResponseWriter, r *http.Request) {
_ = writePage(w, pageCreate())
}
func (h *handler) handleDoCreate(w http.ResponseWriter, r *http.Request) {
earliest, err := time.Parse(dateFmt, r.FormValue(fieldNameEarliest))
if err != nil {
fmt.Fprint(w, "bad earliest date")
return
}
latest, err := time.Parse(dateFmt, r.FormValue(fieldNameLatest))
if err != nil {
fmt.Fprint(w, "bad latest date")
return
}
eventName := r.FormValue(fieldNameEventName)
if eventName == "" {
fmt.Fprint(w, "event name is required")
return
}
description := r.FormValue(fieldNameDescription)
_ = writePage(w, pageDoCreate(eventName, description, earliest, latest))
}
func (h *handler) handleAdmin(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
_ = writePage(w, pageAdmin(query.Get(keyEventID), query.Get(keyAdminCode)))
}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.mux.ServeHTTP(w, r)
}
func writePage(w io.Writer, contents h.Term) error { func writePage(w io.Writer, contents h.Term) error {
page := e.Html()( page := e.Html()(
e.Head()( e.Head()(
@ -196,41 +249,9 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
mux := http.NewServeMux()
mux.HandleFunc(pathRoot, func(w http.ResponseWriter, r *http.Request) {
_ = writePage(w, pageRoot())
})
mux.HandleFunc(pathCreate, func(w http.ResponseWriter, r *http.Request) {
_ = writePage(w, pageCreate())
})
mux.HandleFunc(pathDoCreate, func(w http.ResponseWriter, r *http.Request) {
earliest, err := time.Parse(dateFmt, r.FormValue(fieldNameEarliest))
if err != nil {
fmt.Fprint(w, "bad earliest date")
return
}
latest, err := time.Parse(dateFmt, r.FormValue(fieldNameLatest))
if err != nil {
fmt.Fprint(w, "bad latest date")
return
}
eventName := r.FormValue(fieldNameEventName)
if eventName == "" {
fmt.Fprint(w, "event name is required")
return
}
description := r.FormValue(fieldNameDescription)
_ = writePage(w, pageDoCreate(eventName, description, earliest, latest))
})
mux.HandleFunc(pathAdmin, func(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
_ = writePage(w, pageAdmin(query.Get(keyEventID), query.Get(keyAdminCode)))
})
srv := http.Server{ srv := http.Server{
Addr: Addr, Addr: Addr,
Handler: mux, Handler: NewHandler(),
} }
log.Println(srv.ListenAndServe()) log.Println(srv.ListenAndServe())
} }