rework template load/generation + add generic error on template error

This commit is contained in:
rmanach
2025-01-07 16:55:36 +01:00
parent 40e08154f6
commit 708db35214
13 changed files with 501 additions and 449 deletions
+17 -52
View File
@@ -1,39 +1,18 @@
package home
import (
"bytes"
"fmt"
"librapi/services"
"librapi/templates"
"net/http"
"github.com/rs/zerolog/log"
"librapi/forms"
"librapi/services"
"librapi/templates"
)
const URL = "/"
type SearchField struct {
Name string
Value string
Err string
}
type SearchForm struct {
Search SearchField
Error error
Method string
Results []services.BookMetadata
}
func NewSearchForm() SearchForm {
return SearchForm{
Search: SearchField{
Name: "search",
},
Method: http.MethodPost,
}
}
func Handler(bs services.IStore) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
@@ -48,52 +27,38 @@ func Handler(bs services.IStore) func(http.ResponseWriter, *http.Request) {
}
func getHome(w http.ResponseWriter, _ *http.Request) {
home := templates.GetHome()
buf := bytes.NewBufferString("")
if err := home.Execute(buf, &SearchForm{}); err != nil {
log.Err(err).Msg("unable to generate template")
http.Error(w, "unexpected error occurred", http.StatusInternalServerError)
tmpl, err := templates.ExecuteHomeTmpl(&forms.SearchForm{}, w)
if err != nil {
log.Err(err).Msg("unable to generate home template")
return
}
fmt.Fprint(w, buf)
}
func extractSearchForm(r *http.Request) SearchForm {
sf := NewSearchForm()
sf.Search.Value = r.FormValue(sf.Search.Name)
return sf
fmt.Fprint(w, tmpl)
}
func postHome(w http.ResponseWriter, r *http.Request, bs services.IStore) {
home := templates.GetHome()
buf := bytes.NewBufferString("")
sf := extractSearchForm(r)
sf := forms.SearchFormFromRequest(r)
bms, err := bs.Search(sf.Search.Value)
if err != nil {
sf.Error = err
if err := home.Execute(buf, sf); err != nil {
log.Err(err).Msg("unable to generate template")
http.Error(w, "unexpected error occurred", http.StatusInternalServerError)
tmpl, err := templates.ExecuteHomeTmpl(&sf, w)
if err != nil {
log.Err(err).Msg("unable to generate home template")
return
}
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, buf.String())
fmt.Fprint(w, tmpl)
return
}
sf.Results = bms
if err := home.Execute(buf, sf); err != nil {
log.Err(err).Msg("unable to generate template")
http.Error(w, "unexpected error occurred", http.StatusInternalServerError)
tmpl, err := templates.ExecuteHomeTmpl(&sf, w)
if err != nil {
log.Err(err).Msg("unable to generate home template")
return
}
fmt.Fprint(w, buf)
fmt.Fprint(w, tmpl)
}