-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathJSONpipe.go
79 lines (64 loc) · 1.46 KB
/
JSONpipe.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
package jsonpipe
import (
"bufio"
"encoding/json"
"log"
"net"
)
type JSONpipe struct {
actions map[string]Action
port string
}
type Action struct {
h Handler
pattern string
}
type Handler func(*json.RawMessage) (map[string]interface{}, error)
// NewServeMux allocates and returns a new ServeMux.
func NewJSONpipe() *JSONpipe {
return &JSONpipe{
actions: make(map[string]Action),
}
}
// our pipe instance
var Pipe = NewJSONpipe()
func Handle(action string, handler Handler) {
if action == "" {
panic("jsonstream: action can't be an empty string")
}
if handler == nil {
panic("jsonstream: nil handler")
}
// check for an already created entry
if _, ok := Pipe.actions[action]; ok {
panic("jsonstream: action " + action + " already exists")
}
// register the action in our map
Pipe.actions[action] = Action{pattern: action, h: handler}
}
// pass in the port to bind to. ie. :8080
func ListenAndServe(port string) {
ln, err := net.Listen("tcp", port)
if err != nil {
log.Fatal(err)
}
defer ln.Close()
Pipe.port = port
log.Println("jsonstream listening on localhost" + port)
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
// handle error
continue
}
server := Server{
Conn: conn,
Reader: bufio.NewReader(conn),
Encoder: json.NewEncoder(conn),
}
log.Println("new connection from " + server.Conn.RemoteAddr().String())
// create a new go routine for each connection
go server.Read()
}
}