-
Notifications
You must be signed in to change notification settings - Fork 14
/
suggest_handler.go
52 lines (42 loc) · 1008 Bytes
/
suggest_handler.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
package main
import (
"encoding/json"
"net/http"
"github.com/stevenferrer/solr-go"
)
type suggestHandler struct {
collection string
solrClient solr.Client
}
type suggestion struct {
Term string `json:"term"`
}
func (h *suggestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query().Get("q")
if len(q) == 0 {
return
}
dict := "default"
suggestParams := solr.NewSuggesterParams("suggest").
Build().Query(q).Dictionaries(dict)
suggestResp, err := h.solrClient.Suggest(r.Context(), h.collection, suggestParams)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
suggest := *suggestResp.Suggest
termBody := suggest[dict][q]
suggestions := []suggestion{}
for _, suggest := range termBody.Suggestions {
suggestions = append(suggestions, suggestion{
Term: suggest.Term,
})
}
err = json.NewEncoder(w).Encode(solr.M{
"numFound": termBody.NumFound,
"suggestions": suggestions,
})
if err != nil {
http.Error(w, err.Error(), 500)
}
}