-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
239 lines (201 loc) · 5.17 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package main
import (
"compress/gzip"
"embed"
"encoding/json"
"flag"
"fmt"
"html/template"
"log"
"net/http"
"strings"
"time"
"github.com/gojp/nihongo/lib/dictionary"
"github.com/golang/gddo/httputil/header"
)
const (
title = "Nihongo.io"
description = "The world's best Japanese dictionary."
)
var (
//go:embed templates/*
content embed.FS
//go:embed data/*
data embed.FS
//go:embed static/*
static embed.FS
)
// Entry is a dictionary entry
type Entry struct {
Word string `json:"word"`
Furigana string `json:"furigana"`
Definition string `json:"definition"`
Common bool `json:"common,omitempty"`
}
var dict dictionary.Dictionary
func initialize() {
file, err := data.Open("data/edict2.json.gz")
if err != nil {
log.Fatal("Could not load edict2.json.gz: ", err)
}
defer file.Close()
reader, err := gzip.NewReader(file)
if err != nil {
log.Fatal("Could not create reader: ", err)
}
dict, err = dictionary.Load(reader)
if err != nil {
log.Fatal("Could not load dictionary: ", err)
}
}
type templateData struct {
Search string `json:"search"`
Entries []Entry `json:"entries"`
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
// defer timeTrack(time.Now(), "/")
if r.URL.Path[1:] != "" {
http.NotFound(w, r)
return
}
data := templateData{
Entries: []Entry{},
Search: "",
}
jsonData, err := json.Marshal(data)
if err != nil {
log.Println("ERROR:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
m := map[string]interface{}{
"json": template.HTML(string(jsonData)),
"data": data,
"title": title,
"description": description,
}
t, err := template.ParseFS(content, "templates/home.html")
if err != nil {
log.Println("ERROR:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = t.ExecuteTemplate(w, "home.html", m)
if err != nil {
log.Println("ERROR:", err)
}
}
func search(w http.ResponseWriter, r *http.Request) {
// check GET and POST parameters for "text" field
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
text := r.Form.Get("text")
trackText := fmt.Sprintf("/search?text=%s", text)
// if no "text" field is present, we check the URL
if text == "" {
text = strings.TrimPrefix(r.URL.Path, "/search/")
trackText = fmt.Sprintf("/search/%s", text)
}
defer timeTrack(time.Now(), trackText)
// if we still don't have text, we redirect to the home page
if text == "" {
log.Println("Redirecting to home")
http.Redirect(w, r, "/", http.StatusMovedPermanently)
}
// get the entries that match our text
entries := []Entry{}
results := dict.Search(text, 10)
for _, r := range results {
var defs []string
for _, g := range r.Glosses {
defs = append(defs, g.English)
}
entries = append(entries, Entry{
Word: r.Japanese,
Furigana: r.Furigana,
Definition: strings.Join(defs, "; "),
Common: r.Common,
})
}
data := templateData{
Search: text,
Entries: entries,
}
jsonData, err := json.Marshal(data)
if err != nil {
log.Println("ERROR:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
isXMLHTTP := r.Header.Get("X-Requested-With") == "XMLHttpRequest"
accepts := header.ParseAccept(r.Header, "Accept")
wantsJSON, wantsHTML := 0.0, 0.0
for _, acc := range accepts {
switch acc.Value {
case "text/json", "application/json":
wantsJSON = acc.Q
case "text/html":
wantsHTML = acc.Q
}
}
if isXMLHTTP || wantsJSON > wantsHTML {
w.Header().Set("Content-Type", "application/json")
b := []byte(template.HTML(string(jsonData)))
w.Write(b)
return
}
pageTitle := text + " in Japanese | " + title
description := fmt.Sprintf("Japanese to English for %s", text)
if len(data.Entries) > 0 {
e := data.Entries[0]
description = fmt.Sprintf("%s (%s) - %s", e.Word, e.Furigana, e.Definition)
}
m := map[string]interface{}{
"json": template.HTML(string(jsonData)),
"data": data,
"title": pageTitle,
"description": description,
}
t, err := template.ParseFS(content, "templates/home.html")
if err != nil {
log.Println("ERROR:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = t.ExecuteTemplate(w, "home.html", m)
if err != nil {
log.Println("ERROR:", err)
}
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFS(content, "templates/*.html")
if err != nil {
log.Println("ERROR:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = t.ExecuteTemplate(w, "about.html", nil)
if err != nil {
log.Println("ERROR:", err)
}
}
func main() {
var addr string
flag.StringVar(&addr, "addr", "127.0.0.1:8080", "address to run on")
flag.Parse()
initialize()
http.HandleFunc("/", homeHandler)
http.HandleFunc("/search", search)
http.HandleFunc("/search/", search)
http.HandleFunc("/about", aboutHandler)
http.Handle("/static/", http.FileServer(http.FS(static)))
log.Printf("Running on %s ...", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}
func timeTrack(start time.Time, name string) {
elapsed := time.Since(start)
log.Printf("%s took %s", name, elapsed)
}