-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
239 lines (201 loc) · 5.02 KB
/
main.go
File metadata and controls
239 lines (201 loc) · 5.02 KB
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 (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"github.com/gorilla/mux"
"github.com/tiltfactor/simish/domain"
"github.com/tiltfactor/simish/impl"
"github.com/tiltfactor/simish/test"
"github.com/urfave/cli"
)
type inputData map[string]string
// App holds the db structure. Used for dep injection.
type App struct {
db domain.InputOutputStore
}
type response struct {
Input string `json:"input"`
Response string `json:"response"`
Match string `json:"match,omitempty"`
Room string `json:"room"`
Score float64 `json:"score"`
AiCol int64 `json:"aiCol"`
ResultType int64 `json:"resultType"`
}
func (r response) String() string {
return fmt.Sprintf("Input: %s, Matched: %s, Score: %f, Response: %s, Room: %s",
r.Input, r.Match, r.Score, r.Response, r.Room)
}
type rawData struct {
Text string `json:"text"`
Reply string `json:"reply"`
}
// ResponseHandler handles the user request for a input output pair
func (a App) ResponseHandler(w http.ResponseWriter, r *http.Request) {
vars := r.URL.Query()
input := vars["input"]
room := vars["room"]
if len(room) < 1 {
http.Error(w, "Must provide room number", 400)
return
}
roomNumber, err := strconv.ParseInt(room[0], 10, 64)
if err != nil {
http.Error(w, "Room number must be an int", 400)
return
}
io, score := a.db.Response(input[0], roomNumber)
resp := response{
Input: input[0],
Response: io.Output,
Match: io.Input,
Room: room[0],
Score: score,
AiCol: io.AiCol,
ResultType: io.ResultType,
}
log.Println(resp)
data, err := json.Marshal(resp)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
// DBConfig is used to import the db_cfg.json file
type DBConfig struct {
User string `json:"username"`
Pass string `json:"password"`
IP string `json:"ip_addr"`
Port string `json:"db_port"`
DB string `json:"database"`
ServerPort string `json:"server_port"`
}
func (cfg *DBConfig) connectionString() string {
connStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", cfg.User, cfg.Pass, cfg.IP, cfg.Port, cfg.DB)
log.Println(connStr)
return connStr
}
func startSimish(c *cli.Context) error {
cfgFile, err := ioutil.ReadFile("./db_cfg.json")
if err != nil {
log.Fatal(err)
}
cfg := &DBConfig{}
if err := json.Unmarshal(cfgFile, cfg); err != nil {
log.Fatal(err)
}
store, err := impl.NewSQLStore(cfg.connectionString())
if err != nil {
log.Fatal(err)
}
app := App{db: store}
r := mux.NewRouter()
// Routes consist of a path and a handler function.
r.HandleFunc("/api/v1/response", app.ResponseHandler)
// Bind to a port and pass our router in
log.Println("Running on port:", cfg.ServerPort)
logFile, err := os.OpenFile("logs", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatal("Could not open log file")
}
defer logFile.Close()
log.SetOutput(logFile)
if err := http.ListenAndServe(":"+cfg.ServerPort, r); err != nil {
log.Fatal(err)
}
return nil
}
func readInput(prompt string) string {
scan := bufio.NewScanner(os.Stdin)
fmt.Print(prompt + " ")
scan.Scan()
return scan.Text()
}
func createCfg(c *cli.Context) error {
fmt.Println("Follow along to create a db_cfg.")
fmt.Println("Warning: This will overwrite existing db_cfg.json file")
f, err := os.Create("./db_cfg.json")
if err != nil {
log.Fatal(err)
}
defer f.Close()
serverPort := readInput("Port to run Simish on:")
user := readInput("MySQL database username:")
pass := readInput("MySQL database password:")
ip := readInput("MySQL database IP address:")
port := readInput("MySQL database port:")
db := readInput("MySQL database name:")
cfg := DBConfig{
ServerPort: serverPort,
User: user,
Pass: pass,
IP: ip,
DB: db,
Port: port,
}
cm, err := json.MarshalIndent(&cfg, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println()
fmt.Println(string(cm))
w := bufio.NewWriter(f)
if _, err := w.Write(cm); err != nil {
log.Fatal(err)
}
w.Flush()
fmt.Println("Successfully created db_cfg.json")
return nil
}
func runTest(c *cli.Context) {
cfgFile, err := ioutil.ReadFile("./db_cfg.json")
if err != nil {
log.Fatal(err)
}
cfg := &DBConfig{}
if err := json.Unmarshal(cfgFile, cfg); err != nil {
log.Fatal(err)
}
store, err := impl.NewSQLStore(cfg.connectionString())
if err != nil {
log.Fatal(err)
}
pairs := store.GetAllPairs(1)
args := c.Args()
if len(args) > 2 {
log.Fatal("Too many arguments")
}
test.RunSoftMatch(args, pairs)
}
func main() {
app := cli.NewApp()
app.Name = "Simish"
app.Usage = "Soft Matching Algorithm as a service"
app.Version = "0.5.0"
app.Commands = []cli.Command{
{
Name: "init",
Usage: "Create db_cfg.json file",
Action: createCfg,
},
{
Name: "start",
Usage: "Start the simish server",
Action: startSimish,
},
{
Name: "test",
Usage: "Test the softmatch algorithm",
Action: runTest,
},
}
app.Run(os.Args)
}