-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.go
86 lines (76 loc) · 1.38 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
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"trie"
)
const (
PORT = 8080 //服务监听端口
FILENAME = "badwords.txt" //敏感词库
)
var T *trie.Trie
//导入过滤词库
func importWords(T *trie.Trie, file string) (err error) {
rd, err := os.Open(file)
if err != nil {
return
}
defer rd.Close()
r := bufio.NewReader(rd)
for {
line, isPrefix, e := r.ReadLine()
if e != nil {
if e != io.EOF {
err = e
}
break
}
if isPrefix {
continue
}
if word := strings.TrimSpace(string(line)); word != "" {
T.Add(word)
}
}
return
}
//HTTP请求处理器
func mainHandler(w http.ResponseWriter, r *http.Request) {
content := r.FormValue("content")
result, find := T.Replace(content)
m := make(map[string]interface{})
m["result"] = result
m["find"] = find
if len(find) > 0 {
m["ret"] = 1
} else {
m["ret"] = 0
}
bytes, err := json.Marshal(m)
if err == nil {
w.Write(bytes)
} else {
log.Println(err.Error())
}
}
func main() {
var err error
T = trie.NewTrie()
err = importWords(T, FILENAME)
if err != nil {
log.Fatalln(err.Error())
} else {
log.Printf("服务正在启动,监听端口: %d ...\n", PORT)
http.HandleFunc("/", mainHandler)
err = http.ListenAndServe(fmt.Sprintf(":%d", PORT), nil)
if err != nil {
log.Fatalln("启动失败: ", err.Error())
}
}
}