-
Notifications
You must be signed in to change notification settings - Fork 16
/
jsonrpc.go
84 lines (69 loc) · 1.79 KB
/
jsonrpc.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
package jsonrpc
import (
"bufio"
"errors"
"io"
"log"
"net"
"net/http"
"net/rpc"
"net/rpc/jsonrpc"
)
var jsonRpcConnected = "200 Connected to JSON RPC"
type Server struct {
*rpc.Server
}
func NewServer() *Server {
return &Server{rpc.NewServer()}
}
func (server *Server) Accept(lis net.Listener) {
for {
conn, err := lis.Accept()
if err != nil {
log.Fatal("rpc.Serve: accept:", err.Error()) // TODO(r): exit?
}
go server.ServeConn(conn)
}
}
func (server *Server) ServeConn(conn io.ReadWriteCloser) {
server.ServeCodec(jsonrpc.NewServerCodec(conn))
}
func (server *Server) HandleHTTP(rpcPath string) {
http.Handle(rpcPath, server)
}
func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
var conn, _, err = w.(http.Hijacker).Hijack()
if err != nil {
log.Print("rpc hijacking ", req.RemoteAddr, ": ", err.Error())
return
}
io.WriteString(conn, "HTTP/1.1 "+jsonRpcConnected+"\n")
//io.WriteString(conn, "Access-Control-Allow-Origin: *\n")
io.WriteString(conn, "Content-Type: application/json\n\n")
server.ServeCodec(jsonrpc.NewServerCodec(conn))
}
func Dial(network, address string) (*rpc.Client, error) {
return jsonrpc.Dial(network, address)
}
func DialHTTP(network, address, path string) (*rpc.Client, error) {
var err error
conn, err := net.Dial(network, address)
if err != nil {
return nil, err
}
io.WriteString(conn, "GET "+path+" HTTP/1.1\n\n")
// Require successful HTTP response
// before switching to RPC protocol.
resp, err := http.ReadResponse(bufio.NewReader(conn), nil)
if err == nil {
if resp.Status == jsonRpcConnected {
return jsonrpc.NewClient(conn), nil
}
}
conn.Close()
return nil, &net.OpError{
Op: "JsonRPC dial to",
Net: network + "://" + address,
Err: errors.New("unexpected HTTP response: " + resp.Status),
}
}