Commit 57e16763 authored by Riccardo Setti's avatar Riccardo Setti
Browse files

add /search_api endpoint to return search results in json format

refactor handleSearch() for remove the databse query code to is own
method.
parent 034e11ae
......@@ -70,23 +70,43 @@ func (p *pagination) End() int {
return end + 1
}
func (s *uiServer) handleSearch(w http.ResponseWriter, req *http.Request) {
var pageSize = 15
func executeSearch(s *uiServer, req *http.Request) (*SearchResult, error) {
query := req.FormValue("q")
page, _ := strconv.Atoi(req.FormValue("p"))
pageSize := 15
pageSize := pageSize
result, err := s.db.Search(query, page*pageSize, pageSize)
return result, err
}
func (s *uiServer) handleApiSearch(w http.ResponseWriter, req *http.Request){
result, _ := executeSearch(s, req)
books := []*flatBook{}
for id := range result.Results {
book := flatten(result.Results[id])
books = append(books, book)
}
json, _ := json.Marshal(books)
fmt.Fprint(w, string(json))
}
func (s *uiServer) handleSearch(w http.ResponseWriter, req *http.Request) {
result, err := executeSearch(s, req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
page, _ := strconv.Atoi(req.FormValue("p"))
ctx := struct {
Query string
Results []*Book
Pagination *pagination
}{
Query: query,
Query: req.FormValue("q"),
Results: result.Results,
Pagination: &pagination{
PageSize: pageSize,
......@@ -384,6 +404,7 @@ func NewHttpServer(db *Database, storage, cache *RWFileStorage, addr string) *ht
r.HandleFunc("/opensearch.xml", handleOpenSearchXml)
r.HandleFunc("/suggest", uisrv.handleSuggest)
r.HandleFunc("/search", uisrv.handleSearch)
r.HandleFunc("/search_api", uisrv.handleApiSearch)
r.HandleFunc("/", uisrv.handleHome)
return &http.Server{
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment