forked from ponzu-cms/ponzu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.go
109 lines (93 loc) · 2.23 KB
/
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package api
import (
"encoding/json"
"log"
"net/http"
"net/url"
"strconv"
"github.com/timezstyle/ponzu/system/db"
"github.com/timezstyle/ponzu/system/item"
"github.com/timezstyle/ponzu/system/search"
)
func searchContentHandler(res http.ResponseWriter, req *http.Request) {
qs := req.URL.Query()
t := qs.Get("type")
// type must be set, future version may compile multi-type result set
if t == "" {
res.WriteHeader(http.StatusBadRequest)
return
}
it, ok := item.Types[t]
if !ok {
res.WriteHeader(http.StatusBadRequest)
return
}
if hide(res, req, it()) {
return
}
q, err := url.QueryUnescape(qs.Get("q"))
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
// q must be set
if q == "" {
res.WriteHeader(http.StatusBadRequest)
return
}
count, err := strconv.Atoi(qs.Get("count")) // int: determines number of posts to return (10 default, -1 is all)
if err != nil {
if qs.Get("count") == "" {
count = 10
} else {
res.WriteHeader(http.StatusInternalServerError)
return
}
}
offset, err := strconv.Atoi(qs.Get("offset")) // int: multiplier of count for pagination (0 default)
if err != nil {
if qs.Get("offset") == "" {
offset = 0
} else {
res.WriteHeader(http.StatusInternalServerError)
return
}
}
// execute search for query provided, if no index for type send 404
matches, err := search.TypeQuery(t, q, count, offset)
if err == search.ErrNoIndex {
res.WriteHeader(http.StatusNotFound)
return
}
if err != nil {
log.Println("[search] Error:", err)
res.WriteHeader(http.StatusInternalServerError)
return
}
// respond with json formatted results
bb, err := db.ContentMulti(matches)
if err != nil {
log.Println("[search] Error:", err)
res.WriteHeader(http.StatusInternalServerError)
return
}
// if we have matches, push the first as its matched by relevance
if len(bb) > 0 {
push(res, req, it(), bb[0])
}
var result = []json.RawMessage{}
for i := range bb {
result = append(result, bb[i])
}
j, err := fmtJSON(result...)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
j, err = omit(res, req, it(), j)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
sendData(res, req, j)
}