-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.go
130 lines (104 loc) · 2.32 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package ironclad
import (
"net/http"
"sort"
"strconv"
"strings"
"sync"
"golang.org/x/net/context"
)
type Engine struct {
sync.Mutex
}
func (e *Engine) Search(
c context.Context,
query string,
category Category,
order SortOrder,
) ([]Listing, map[Category]int, error) {
e.Lock()
defer e.Unlock()
listings, err := scan(c)
if err != nil {
return nil, nil, err
}
results := []Listing{}
categories := map[Category]int{}
for _, listing := range listings {
if listing.Matches(query) {
if listing.Category == category {
results = append(results, listing)
}
categories[listing.Category]++
}
}
sort.Sort(byOrder{results, order})
return results, categories, nil
}
func Paginate(listings []Listing, offset int) (prev, off, next int) {
off = offset
if off >= len(listings) {
off = len(listings)
}
if off < 0 {
off = 0
}
next = off + 100
if next >= len(listings) {
next = len(listings)
}
prev = off - 100
if prev < 0 {
prev = 0
}
return
}
func (l Listing) Matches(query string) bool {
return strings.Contains(strings.ToLower(l.Title), strings.ToLower(query))
}
// define how results are shown
var engine Engine
type SearchResults struct {
Previous, Offset, Next, Total int
Listings []Listing
Categories map[Category]int
ChangeCategory bool
Common
}
func (r SearchResults) Template() string { return "SearchResults.html" }
func (r SearchResults) NewURL() string {
if r.ChangeCategory {
return "/" + r.Common.URLSuffix()
}
return ""
}
func SearchListings(s *Subject, c context.Context, r *http.Request) (Template, error) {
com := NewCommon(s, r)
results, cats, err := engine.Search(c, com.Query, com.Category, com.Order)
if err != nil {
return nil, err
}
off, _ := strconv.ParseInt(r.FormValue("offset"), 10, 64)
previous, offset, next := Paginate(results, int(off))
page := SearchResults{
Previous: previous,
Offset: offset,
Next: next,
Total: len(results),
Listings: results[offset:next],
Categories: cats,
Common: com,
}
// if we could have shown results, but didn't, because we were
// in a weird category, redirect to the right one
if len(results) == 0 {
for _, category := range AllCategories {
if cats[category] > 0 {
page.Common.Category = category
page.ChangeCategory = true
break
}
}
}
return page, nil
}