package home import ( "bytes" "fmt" "librapi/services" "librapi/templates" "net/http" "github.com/rs/zerolog/log" ) 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 { 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) { 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) 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 } fmt.Fprint(w, buf) }