-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
101 lines (81 loc) · 2.01 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
package main
import (
"bufio"
"encoding/json"
"flag"
"log"
"net"
)
var port = flag.String("port", "8888", "port to connect to")
type Client struct {
Conn net.Conn
Req map[string]interface{}
Res map[string]interface{}
}
func main() {
flag.Parse()
ln, err := net.Listen("tcp", ":"+*port)
if err != nil {
log.Fatal(err.Error())
}
log.Println("Listening on localhost:" + *port)
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err.Error())
break
}
// create a new go routine for each connection
go handleConnection(conn)
}
}
// we have a connection, now listen for incoming JSON data
func handleConnection(conn net.Conn) {
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
client := Client{
Conn: conn,
}
var reqData map[string]interface{}
err := json.Unmarshal(scanner.Bytes(), &reqData)
if err != nil {
log.Println(err)
client.Res = map[string]interface{}{
"success": false,
"error": "JSON decode fail - " + err.Error(),
}
go handleResponse(client)
continue
}
// add our decoded JSON data to our client struct
client.Req = reqData
// check for a reqId. this is how the client knows what response
// goes with what request
if client.Req["reqId"] == "" || client.Req["reqId"] == nil {
client.Res = map[string]interface{}{
"success": false,
"error": "reqId not provided",
}
go handleResponse(client)
continue
}
// create a new go routine for each request on this connection
go handleRequest(client)
}
}
func handleRequest(client Client) {
// application logic routing goes here.
// when the appliction logic is done, save the response to client.Res
// Example: copy req to res to demo an echo server
client.Res = client.Req
handleResponse(client)
}
func handleResponse(client Client) {
// encode our response to JSON
json, err := json.Marshal(client.Res)
if err != nil {
log.Println("json marshal error. response data: ", client.Res)
}
// send a response to the client
_, err = client.Conn.Write(json)
}