2020-06-26 18:26:10 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"net/http"
|
|
|
|
|
|
2021-11-04 09:03:25 +08:00
|
|
|
"github.com/stevenferrer/solr-go"
|
2020-06-26 18:26:10 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type suggestHandler struct {
|
|
|
|
|
collection string
|
|
|
|
|
solrClient solr.Client
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-10 09:52:07 +08:00
|
|
|
type suggestion struct {
|
|
|
|
|
Term string `json:"term"`
|
|
|
|
|
}
|
|
|
|
|
|
2020-06-26 18:26:10 +08:00
|
|
|
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"
|
2021-02-10 09:52:07 +08:00
|
|
|
suggestParams := solr.NewSuggesterParams("suggest").
|
|
|
|
|
Build().Query(q).Dictionaries(dict)
|
|
|
|
|
suggestResp, err := h.solrClient.Suggest(r.Context(), h.collection, suggestParams)
|
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]
|
|
|
|
|
|
2021-02-10 09:52:07 +08:00
|
|
|
suggestions := []suggestion{}
|
2020-06-26 18:26:10 +08:00
|
|
|
for _, suggest := range termBody.Suggestions {
|
2021-02-10 09:52:07 +08:00
|
|
|
suggestions = append(suggestions, suggestion{
|
|
|
|
|
Term: suggest.Term,
|
|
|
|
|
})
|
2020-06-26 18:26:10 +08:00
|
|
|
}
|
|
|
|
|
|
2021-02-10 09:52:07 +08:00
|
|
|
err = json.NewEncoder(w).Encode(solr.M{
|
2020-06-26 18:26:10 +08:00
|
|
|
"numFound": termBody.NumFound,
|
|
|
|
|
"suggestions": suggestions,
|
2021-02-10 09:52:07 +08:00
|
|
|
})
|
2020-06-26 18:26:10 +08:00
|
|
|
if err != nil {
|
|
|
|
|
http.Error(w, err.Error(), 500)
|
|
|
|
|
}
|
|
|
|
|
}
|