Add result truncation

main
Elnu 2 years ago
parent 36710478f2
commit b6d3b703c9

@ -69,10 +69,11 @@ func ParseEntry(entry jmdict.JmdictEntry) Entry {
}
}
func Search(query string) (exactResults []Entry, otherResults []Entry) {
func Search(query string) (exactResults []Entry, otherResults []Entry, truncated bool) {
query = strings.TrimSpace(query)
exactResults = make([]Entry, 0)
otherResults = make([]Entry, 0)
count := 0
for _, jmdictEntry := range dict.Entries {
exactMatch := false
for _, kanji := range jmdictEntry.Kanji {
@ -98,6 +99,11 @@ func Search(query string) (exactResults []Entry, otherResults []Entry) {
} else {
otherResults = append(otherResults, entry)
}
count++
if count >= 500 {
truncated = true
break
}
}
return
}
@ -105,13 +111,15 @@ func Search(query string) (exactResults []Entry, otherResults []Entry) {
type searchTemplateData struct {
ExactResults []Entry
OtherResults []Entry
Truncated bool
Count int
}
func initSearchTemplateData(exactResults []Entry, otherResults []Entry) searchTemplateData {
func initSearchTemplateData(exactResults []Entry, otherResults []Entry, truncated bool) searchTemplateData {
return searchTemplateData{
ExactResults: exactResults,
OtherResults: otherResults,
Truncated: truncated,
Count: len(exactResults) + len(otherResults),
}
}
@ -156,7 +164,7 @@ func main() {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
r.ParseMultipartForm(0)
query := r.FormValue("q")
exactResults, otherResults := Search(query)
exactResults, otherResults, _ := Search(query)
jsonBytes, _ := json.Marshal(append(exactResults, otherResults...))
fmt.Fprint(w, string(jsonBytes))
return false

@ -1,5 +1,5 @@
{{- define "search" -}}
<p><i>{{ if eq .Count 0 }}No results{{ else }}{{ .Count }} result{{ if ne .Count 1}}s{{ end }}{{ end }}.</i></p>
<p><i>{{ if .Truncated }}Truncated results, showing first {{ .Count }}{{ else }}{{ if eq .Count 0 }}No results{{ else }}{{ .Count }} result{{ if ne .Count 1}}s{{ end }}{{ end }}{{ end }}.</i></p>
{{- range .ExactResults -}}
{{- template "word" . -}}
{{- end }}