-
Notifications
You must be signed in to change notification settings - Fork 51
/
test_web.go
90 lines (70 loc) · 1.76 KB
/
test_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
package main
import (
"./darts"
"encoding/json"
"fmt"
"log"
"net/http"
//"strings"
// "path"
)
type ValueJson struct {
Value string `json:"value"`
}
func dartsInit() (darts.Darts, error) {
d, err := darts.Import("data.txt", "data.lib")
if err != nil {
fmt.Println("ERROR: darts initial failed!")
} else {
fmt.Println("INFO: darts initial success!")
}
return d, err
}
var dart, err = dartsInit()
func simpleSuggest(w http.ResponseWriter, r *http.Request) {
// valueList := make([]ValueJson, 10)
var valueList []ValueJson
r.ParseForm() //解析参数,默认是不会解析的
keyword := r.Form["keyword"]
fmt.Println("keyword:", keyword)
if len(keyword) == 0 {
} else {
results := dart.Search([]rune(keyword[0]), 0)
for i := 0; i < len(results); i++ {
var value ValueJson
value.Value = string(results[i].Key)
valueList = append(valueList, value)
}
}
if len(valueList) > 10 {
valueList = valueList[:10]
}
fmt.Println("return", valueList)
if len(valueList) > 0 {
b, err := json.Marshal(valueList)
if err != nil {
fmt.Println("json err:", err)
}
fmt.Fprintf(w, string(b)) //这个写入到w的是输出到客户端的
} else {
fmt.Fprintf(w, "[]") //这个写入到w的是输出到客户端的
}
return
}
func index(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "templates/index.html")
}
func main() {
// index
http.HandleFunc("/", index) //设置访问的路由
// suggest
http.HandleFunc("/suggest/", simpleSuggest) //设置访问的路由
// static
http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path[1:])
})
err := http.ListenAndServe("0.0.0.0:9090", nil) //设置监听的端口
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}