-
Notifications
You must be signed in to change notification settings - Fork 1
/
web.go
93 lines (85 loc) · 2.53 KB
/
web.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
package d
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"zliu.org/goutil/rest"
)
func (d *Dictionary) RegisterWeb() {
http.Handle(fmt.Sprintf("/%s/get", d.Name), rest.WithLog(d.GetHandler))
http.Handle(fmt.Sprintf("/%s/match", d.Name),
rest.WithLog(d.PrefixMatchHandler))
http.Handle(fmt.Sprintf("/%s/multimatch", d.Name),
rest.WithLog(d.MultiMatchHandler))
http.Handle(fmt.Sprintf("/%s/multimaxmatch", d.Name),
rest.WithLog(d.MultiMaxMatchHandler))
http.Handle(fmt.Sprintf("/%s/update", d.Name),
rest.WithLog(d.UpdateHandler))
}
func (d *Dictionary) GetHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
word := strings.TrimSpace(r.FormValue("word"))
values, err := d.Get(word)
if err != nil {
rest.MustEncode(w, &rest.RestMessage{"ERROR", err.Error()})
return
}
rest.MustEncode(w, &rest.RestMessage{"OK", values})
}
func (d *Dictionary) PrefixMatchHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
text := strings.TrimSpace(r.FormValue("text"))
ret, err := d.PrefixMatch(text)
if err != nil {
rest.MustEncode(w, &rest.RestMessage{"ERROR", err.Error()})
return
}
rest.MustEncode(w, &rest.RestMessage{"OK", ret})
}
func (d *Dictionary) MultiMatchHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
text := strings.TrimSpace(r.FormValue("text"))
ret, err := d.MultiMatch(text)
if err != nil {
rest.MustEncode(w, &rest.RestMessage{"ERROR", err.Error()})
return
}
rest.MustEncode(w, &rest.RestMessage{"OK", ret})
}
func (d *Dictionary) MultiMaxMatchHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
text := strings.TrimSpace(r.FormValue("text"))
ret, err := d.MultiMaxMatch(text)
if err != nil {
rest.MustEncode(w, &rest.RestMessage{"ERROR", err.Error()})
return
}
rest.MustEncode(w, &rest.RestMessage{"OK", ret})
}
func (d *Dictionary) UpdateHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
replace := strings.TrimSpace(r.FormValue("replace"))
flush := strings.TrimSpace(r.FormValue("flush"))
data := strings.TrimSpace(r.FormValue("json"))
var rec Record
if err := json.Unmarshal([]byte(data), &rec); err != nil {
rest.MustEncode(w, &rest.RestMessage{"ERROR", err.Error()})
return
}
f := d.Update
if replace != "" {
f = d.Replace
}
if err := f(rec.K, rec.V); err != nil {
rest.MustEncode(w, &rest.RestMessage{"ERROR", err.Error()})
return
}
if flush != "" {
if err := d.Save(); err != nil {
rest.MustEncode(w, &rest.RestMessage{"ERROR", err.Error()})
return
}
}
rest.MustEncode(w, &rest.RestMessage{"OK", "done"})
}