2020-06-26 18:26:10 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"net/http"
|
|
|
|
|
|
2020-07-24 19:12:31 +08:00
|
|
|
"github.com/sf9v/solr-go"
|
|
|
|
|
"github.com/sf9v/solr-go/suggester"
|
2020-06-26 18:26:10 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type suggestHandler struct {
|
|
|
|
|
collection string
|
|
|
|
|
solrClient solr.Client
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (h *suggestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
q := r.URL.Query().Get("q")
|
|
|
|
|
|
|
|
|
|
if len(q) == 0 {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2020-06-30 15:52:46 +08:00
|
|
|
dict := "default"
|
|
|
|
|
suggestResp, err := h.solrClient.Suggester().Suggest(r.Context(), h.collection,
|
|
|
|
|
suggester.Params{Query: q, Dictionaries: []string{dict}})
|
2020-06-26 18:26:10 +08:00
|
|
|
if err != nil {
|
|
|
|
|
http.Error(w, err.Error(), 500)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
suggest := *suggestResp.Suggest
|
|
|
|
|
termBody := suggest[dict][q]
|
|
|
|
|
|
|
|
|
|
suggestions := []struct {
|
|
|
|
|
Term string `json:"term"`
|
|
|
|
|
}{}
|
|
|
|
|
for _, suggest := range termBody.Suggestions {
|
|
|
|
|
suggestions = append(suggestions, struct {
|
|
|
|
|
Term string `json:"term"`
|
|
|
|
|
}{Term: suggest.Term})
|
|
|
|
|
}
|
|
|
|
|
|
2020-07-05 21:05:14 +08:00
|
|
|
resp := Map{
|
2020-06-26 18:26:10 +08:00
|
|
|
"numFound": termBody.NumFound,
|
|
|
|
|
"suggestions": suggestions,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
w.Header().Add("content-type", "application/json")
|
|
|
|
|
|
|
|
|
|
err = json.NewEncoder(w).Encode(resp)
|
|
|
|
|
if err != nil {
|
|
|
|
|
http.Error(w, err.Error(), 500)
|
|
|
|
|
}
|
|
|
|
|
}
|