search for a book with a single value
This commit is contained in:
@@ -3,6 +3,7 @@ package home
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"librapi/services"
|
||||
"librapi/templates"
|
||||
"net/http"
|
||||
|
||||
@@ -11,11 +12,35 @@ import (
|
||||
|
||||
const URL = "/"
|
||||
|
||||
func Handler() func(http.ResponseWriter, *http.Request) {
|
||||
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 {
|
||||
case http.MethodGet:
|
||||
getHome(w, r)
|
||||
case http.MethodPost:
|
||||
postHome(w, r, bs)
|
||||
default:
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
}
|
||||
@@ -26,7 +51,45 @@ func getHome(w http.ResponseWriter, _ *http.Request) {
|
||||
home := templates.GetHome()
|
||||
|
||||
buf := bytes.NewBufferString("")
|
||||
if err := home.Execute(buf, nil); err != nil {
|
||||
if err := home.Execute(buf, &SearchForm{}); err != nil {
|
||||
log.Err(err).Msg("unable to generate template")
|
||||
http.Error(w, "unexpected error occurred", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Fprint(w, buf)
|
||||
}
|
||||
|
||||
func extractSearchForm(r *http.Request) SearchForm {
|
||||
sf := NewSearchForm()
|
||||
|
||||
sf.Search.Value = r.FormValue(sf.Search.Name)
|
||||
|
||||
return sf
|
||||
}
|
||||
|
||||
func postHome(w http.ResponseWriter, r *http.Request, bs services.IStore) {
|
||||
home := templates.GetHome()
|
||||
buf := bytes.NewBufferString("")
|
||||
|
||||
sf := extractSearchForm(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)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
fmt.Fprint(w, buf.String())
|
||||
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)
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user