-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
181 lines (147 loc) · 3.37 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
package main
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"time"
)
// default timeout for request in milliseconds
var timeout time.Duration = 1000
var (
stdin io.WriteCloser
stdout io.ReadCloser
b = bytes.NewReader([]byte{})
buf = bufio.NewReader(b)
)
var errEmptyString = errors.New("Empty string")
var version = "unknown"
func main() {
fmt.Printf("mystem-docker %s\n", version)
args := []string{"-i", "--eng-gr", "--weight", "--format=json"}
homonyms, exists := os.LookupEnv("HOMONYMS_DETECTION")
if exists && isTrue(homonyms) {
args = append(args, "-d")
}
glue, exists := os.LookupEnv("GLUE_GRAMMEMES")
if exists && isTrue(glue) {
args = append(args, "-g")
}
dict, exists := os.LookupEnv("USER_DICT")
if exists {
file := fmt.Sprintf("/stem/dict/%s", dict)
if !isDictExist(file) {
log.Fatalf("Can't find user dictionary \"%s\"\n", dict)
}
d := fmt.Sprintf("--fixlist=%s", file)
args = append(args, d)
}
timeLimit, exists := os.LookupEnv("TIMEOUT")
if exists {
v, err := strconv.Atoi(timeLimit)
if err != nil {
log.Fatalln("Timeout must be integer")
}
timeout = time.Duration(v)
}
var err error
if stdin, stdout, err = runMystem(args); err != nil {
log.Fatalf("Error: %v\n", err)
}
defer stdin.Close()
defer stdout.Close()
http.HandleFunc("/mystem", limit(listen))
http.ListenAndServe(":8080", nil)
}
func runMystem(args []string) (io.WriteCloser, io.ReadCloser, error) {
cmd := exec.Command("./mystem", args...)
var err error
if stdin, err = cmd.StdinPipe(); err != nil {
return nil, nil, err
}
if stdout, err = cmd.StdoutPipe(); err != nil {
return nil, nil, err
}
if err = cmd.Start(); err != nil {
return nil, nil, err
}
return stdin, stdout, nil
}
func isTrue(s string) bool {
s = strings.ToLower(s)
return s == "true" || s == "yes"
}
func isDictExist(file string) bool {
if _, err := os.Stat(file); err != nil {
return !os.IsNotExist(err)
}
return true
}
func process(ctx context.Context, text string) (string, error) {
if len(text) == 0 {
return "", errEmptyString
}
resChan := make(chan string)
errChan := make(chan error)
go func() {
defer close(resChan)
defer close(errChan)
fmt.Fprintln(stdin, text)
buf.Reset(stdout)
str, err := buf.ReadString('\n')
if err != nil {
errChan <- err
}
resChan <- strings.TrimSuffix(str, "\n")
}()
select {
case <-ctx.Done():
return "", ctx.Err()
case r := <-resChan:
return r, nil
case err := <-errChan:
return "", err
}
}
func limit(f http.HandlerFunc) http.HandlerFunc {
sema := make(chan struct{}, 1)
return func(w http.ResponseWriter, r *http.Request) {
sema <- struct{}{}
f(w, r)
<-sema
}
}
func listen(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
err := r.ParseForm()
if err != nil {
log.Printf("Error: %v\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s := r.Form.Get("text")
ctx := r.Context()
ctx, cancel := context.WithTimeout(ctx, timeout*time.Millisecond)
p, err := process(ctx, s)
cancel()
if err != nil {
switch err {
case errEmptyString:
http.Error(w, err.Error(), http.StatusNoContent)
default:
http.Error(w, err.Error(), http.StatusInternalServerError)
}
log.Printf("Error: %v\n", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(p))
}