-
-
Notifications
You must be signed in to change notification settings - Fork 66
/
handlers.go
62 lines (49 loc) 路 1.13 KB
/
handlers.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
package rpc
import (
"io"
"log"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// WebSockets JSON-RPC handler
func WebSocket(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer c.Close()
// notify client that conn is open and ok
c.WriteJSON(struct{ Status string }{Status: "connected"})
for {
mtype, reader, err := c.NextReader()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Println(err)
break
}
res := newRequest(reader).Call()
writer, err := c.NextWriter(mtype)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Println(err)
break
}
io.Copy(writer, res)
}
}
// HTTP-POST JSON-RPC handler
func Post(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
res := newRequest(r.Body).Call()
_, err := io.Copy(w, res)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}