1
0
mirror of https://github.com/stevenferrer/multi-select-facet.git synced 2025-11-23 21:54:45 +02:00
Files
multi-select-facet/cmd/api/suggest_handler.go
Steven Ferrer 8664f33a10 improve search and auto-suggest
- include query term in search
- improved autosuggest
2020-06-30 15:52:46 +08:00

55 lines
1.1 KiB
Go

package main
import (
"encoding/json"
"net/http"
"github.com/stevenferrer/solr-go"
"github.com/stevenferrer/solr-go/suggester"
)
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
}
dict := "default"
suggestResp, err := h.solrClient.Suggester().Suggest(r.Context(), h.collection,
suggester.Params{Query: q, Dictionaries: []string{dict}})
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})
}
resp := map[string]interface{}{
"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)
}
}