librapi/handlers/home/handler.go

65 lines
1.3 KiB
Go

package home
import (
"fmt"
"net/http"
"github.com/rs/zerolog/log"
"librapi/forms"
"librapi/services"
"librapi/templates"
)
const URL = "/"
func Handler(bs services.IStore) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
getHome(w, r)
case http.MethodPost:
postHome(w, r, bs)
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
}
func getHome(w http.ResponseWriter, _ *http.Request) {
tmpl, err := templates.ExecuteHomeTmpl(&forms.SearchForm{}, w)
if err != nil {
log.Err(err).Msg("unable to generate home template")
return
}
fmt.Fprint(w, tmpl)
}
func postHome(w http.ResponseWriter, r *http.Request, bs services.IStore) {
sf := forms.SearchFormFromRequest(r)
bms, err := bs.Search(sf.Search.Value)
if err != nil {
sf.Error = err
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, tmpl)
return
}
sf.Results = bms
tmpl, err := templates.ExecuteHomeTmpl(&sf, w)
if err != nil {
log.Err(err).Msg("unable to generate home template")
return
}
fmt.Fprint(w, tmpl)
}