-
Notifications
You must be signed in to change notification settings - Fork 2
/
search.go
95 lines (86 loc) · 2.36 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
package main
import (
"encoding/json"
"github.com/pkg/errors"
"net/http"
"strconv"
"strings"
)
type SearchHandler struct {
craiglistCities []CraigslistCity
}
type searchOptions struct {
UseCraigslist string `json:"use_craigslist"`
Query string `json:"query"`
Bounds string `json:"bounds"`
MinPrice string `json:"price_min"`
MaxPrice string `json:"price_max"`
}
type SearchResult struct {
Vendor string `json:"vendor"`
Title string `json:"title"`
Posted string `json:"posted"`
Price string `json:"price"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
Description string `json:"description"`
URL string `json:"url"`
}
func (h *SearchHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
opts, err := h.parseForm(r)
if err != nil {
http.Error(w, err.Error(), http.StatusNotAcceptable)
return
}
harvesters := make([]Harvester, 0)
if opts.UseCraigslist == "on" {
bounds, err := h.parseBounds(opts.Bounds)
if err != nil {
http.Error(w, err.Error(), http.StatusNotAcceptable)
return
}
harvesters = append(harvesters, &CraigslistHarvester{
options: opts,
cities: FindAllCitiesWithin(h.craiglistCities, bounds),
})
}
results := make([]SearchResult, 0)
for _, harvester := range harvesters {
harvest, err := harvester.Harvest()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
results = append(results, harvest...)
}
b, err := json.Marshal(results)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = w.Write(b)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (h *SearchHandler) parseForm(r *http.Request) (searchOptions, error) {
var searchOptions searchOptions
err := json.NewDecoder(r.Body).Decode(&searchOptions)
if err != nil {
return searchOptions, errors.Wrap(err, "could not parse form")
}
return searchOptions, nil
}
func (h *SearchHandler) parseBounds(bounds string) ([]float64, error) {
parsedBounds := make([]float64, 0, 4)
split := strings.Split(bounds, ",")
for _, bound := range split {
parsed, err := strconv.ParseFloat(bound, 64)
if err != nil {
return nil, errors.Wrap(err, "could not parse bounds")
}
parsedBounds = append(parsedBounds, parsed)
}
return parsedBounds, nil
}