/
handler_search.go
56 lines (47 loc) · 1.22 KB
/
handler_search.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
import (
"net/http"
"github.com/gocql/gocql"
"github.com/skeswa/gophr/common/dtos"
"github.com/skeswa/gophr/common/errors"
"github.com/skeswa/gophr/common/models"
)
const (
queryStringSearchTextKey = "q"
)
// SearchHandler creates an HTTP request handler that responds to fuzzy package
// searches.
func SearchHandler(session *gocql.Session) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
var searchText string
qs := r.URL.Query()
if qs != nil {
searchText = qs.Get(queryStringSearchTextKey)
}
if len(searchText) < 1 {
errors.RespondWithError(w, NewInvalidQueryStringParameterError(
queryStringSearchTextKey,
searchText,
))
return
}
packageModels, err := models.FuzzySearchPackages(session, searchText)
if err != nil {
errors.RespondWithError(w, err)
return
}
packageListDTO := dtos.NewPackageListDTOFromPackageModelList(packageModels)
if len(packageListDTO) > 0 {
json, err := packageListDTO.MarshalJSON()
if err != nil {
errors.RespondWithError(w, err)
return
}
w.WriteHeader(http.StatusOK)
w.Write(json)
} else {
w.WriteHeader(http.StatusOK)
w.Write([]byte(dtos.EmptyListJSON))
}
}
}