diff --git a/dict/main.go b/dict/main.go index a82b718..c2e5dde 100644 --- a/dict/main.go +++ b/dict/main.go @@ -102,6 +102,20 @@ func Search(query string) (exactResults []Entry, otherResults []Entry) { return } +type searchTemplateData struct { + ExactResults []Entry + OtherResults []Entry + Count int +} + +func initSearchTemplateData(exactResults []Entry, otherResults []Entry) searchTemplateData { + return searchTemplateData{ + ExactResults: exactResults, + OtherResults: otherResults, + Count: len(exactResults) + len(otherResults), + } +} + func main() { err := LoadDict() if err != nil { @@ -110,6 +124,29 @@ func main() { } fmt.Println("JMdict loaded!") r := mux.NewRouter() + r.HandleFunc("/", httputils.GenerateHandler( + "index.html", + func(w http.ResponseWriter, r *http.Request) bool { return true }, + func(w http.ResponseWriter, r *http.Request) any { return nil }, + []string{http.MethodGet}, + )) + r.HandleFunc("/search/{query}", httputils.GenerateHandler( + "index.html", + func(w http.ResponseWriter, r *http.Request) bool { + return true + }, + func(w http.ResponseWriter, r *http.Request) any { + query := mux.Vars(r)["query"] + return struct { + Query string + Results searchTemplateData + }{ + Query: query, + Results: initSearchTemplateData(Search(query)), + } + }, + []string{http.MethodGet}, + )) r.HandleFunc("/api/search", httputils.GenerateHandler( "search.html", func(w http.ResponseWriter, r *http.Request) bool { @@ -127,16 +164,7 @@ func main() { func(w http.ResponseWriter, r *http.Request) any { r.ParseMultipartForm(0) query := r.FormValue("q") - exactResults, otherResults := Search(query) - return struct { - ExactResults []Entry - OtherResults []Entry - Count int - }{ - ExactResults: exactResults, - OtherResults: otherResults, - Count: len(exactResults) + len(otherResults), - } + return initSearchTemplateData(Search(query)) }, []string{http.MethodGet, http.MethodPost}, )) diff --git a/dict/static/index.html b/dict/templates/index.html similarity index 65% rename from dict/static/index.html rename to dict/templates/index.html index 3ebf623..a9232e8 100644 --- a/dict/static/index.html +++ b/dict/templates/index.html @@ -19,11 +19,14 @@
- +
-
+
+ {{ with .Results }}{{ template "search" . }}{{ end }} +

diff --git a/dict/templates/search.html b/dict/templates/search.html index a345fe2..0e077d4 100644 --- a/dict/templates/search.html +++ b/dict/templates/search.html @@ -1,3 +1,4 @@ +{{- define "search" -}}

{{ if eq .Count 0 }}No results{{ else }}{{ .Count }} result{{ if ne .Count 1}}s{{ end }}{{ end }}.

{{- range .ExactResults -}} {{- template "word" . -}} @@ -5,4 +6,6 @@
{{ range .OtherResults -}} {{ template "word" . }} -{{- end -}} \ No newline at end of file +{{- end -}} +{{- end -}} +{{- template "search" . -}} \ No newline at end of file