Skip to content

Commit 9b5c1cb

Browse files
committed
Rewrite using "golang.org/x/net/websocket"
- change MethodContext.Args to MethodContext.Params
1 parent a6454e7 commit 9b5c1cb

File tree

9 files changed

+141
-157
lines changed

9 files changed

+141
-157
lines changed

server/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ func main() {
1818
}
1919

2020
func handler(ctx server.MethodContext) {
21-
n, ok := ctx.Args[0].(float64)
21+
n, ok := ctx.Params[0].(float64)
2222

2323
if !ok {
2424
ctx.SendError("invalid parameters")

server/conn.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package server
2+
3+
import "golang.org/x/net/websocket"
4+
5+
type Conn struct {
6+
ws *websocket.Conn
7+
}
8+
9+
func (c *Conn) ReadJSON(msg interface{}) error {
10+
return websocket.JSON.Receive(c.ws, msg)
11+
}
12+
13+
func (c *Conn) WriteJSON(msg interface{}) error {
14+
return websocket.JSON.Send(c.ws, msg)
15+
}

server/integration/integration_test.go renamed to server/integration_test/integration_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ func TestStartServer(t *testing.T) {
3737
s = server.New()
3838

3939
s.Method("double", func(ctx server.MethodContext) {
40-
n, ok := ctx.Args[0].(float64)
40+
n, ok := ctx.Params[0].(float64)
4141

4242
if !ok {
4343
ctx.SendError("invalid parameters")

server/method_context.go

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,37 @@
11
package server
22

3-
import (
4-
"errors"
5-
6-
"golang.org/x/net/websocket"
7-
)
3+
import "errors"
84

95
type MethodContext struct {
106
ID string
11-
Args []interface{}
12-
Conn *websocket.Conn
7+
Params []interface{}
8+
Conn Connection
139
Done bool
1410
Updated bool
1511
}
1612

17-
func NewMethodContext(m Message, ws *websocket.Conn) MethodContext {
13+
func NewMethodContext(m Message, conn Connection) MethodContext {
1814
ctx := MethodContext{}
1915
ctx.ID = m.ID
20-
ctx.Args = m.Params
21-
ctx.Conn = ws
16+
ctx.Params = m.Params
17+
ctx.Conn = conn
2218
return ctx
2319
}
2420

25-
func (ctx *MethodContext) SendResult(r interface{}) error {
21+
func (ctx *MethodContext) SendResult(result interface{}) error {
2622
if ctx.Done {
27-
err := errors.New("already sent results for method")
23+
err := errors.New("results already sent")
2824
return err
2925
}
3026

3127
ctx.Done = true
32-
return websocket.JSON.Send(ctx.Conn, map[string]interface{}{
28+
msg := map[string]interface{}{
3329
"msg": "result",
3430
"id": ctx.ID,
35-
"result": r,
36-
})
31+
"result": result,
32+
}
33+
34+
return ctx.Conn.WriteJSON(msg)
3735
}
3836

3937
func (ctx *MethodContext) SendError(e string) error {
@@ -43,13 +41,15 @@ func (ctx *MethodContext) SendError(e string) error {
4341
}
4442

4543
ctx.Done = true
46-
return websocket.JSON.Send(ctx.Conn, map[string]interface{}{
44+
msg := map[string]interface{}{
4745
"msg": "result",
4846
"id": ctx.ID,
4947
"error": map[string]string{
5048
"error": e,
5149
},
52-
})
50+
}
51+
52+
return ctx.Conn.WriteJSON(msg)
5353
}
5454

5555
func (ctx *MethodContext) SendUpdated() error {
@@ -59,8 +59,10 @@ func (ctx *MethodContext) SendUpdated() error {
5959
}
6060

6161
ctx.Updated = true
62-
return websocket.JSON.Send(ctx.Conn, map[string]interface{}{
62+
msg := map[string]interface{}{
6363
"msg": "updated",
6464
"methods": []string{ctx.ID},
65-
})
65+
}
66+
67+
return ctx.Conn.WriteJSON(msg)
6668
}

server/method_context_test.go

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ import (
66
)
77

88
func TestSendResult(t *testing.T) {
9-
r := &TestResponse{}
10-
ctx := MethodContext{ID: "test-id", Res: r}
9+
conn := &TestConn{}
10+
ctx := MethodContext{ID: "test-id", Conn: conn}
1111
err := ctx.SendResult(100)
1212

1313
expected := map[string]interface{}{
@@ -24,28 +24,28 @@ func TestSendResult(t *testing.T) {
2424
t.Error("context must set that a result is sent")
2525
}
2626

27-
if !reflect.DeepEqual(r._data, expected) {
27+
if !reflect.DeepEqual(conn.out, expected) {
2828
t.Error("invalid response for method result")
2929
}
3030
}
3131

3232
func TestSendResultWhenDone(t *testing.T) {
33-
r := &TestResponse{}
34-
ctx := MethodContext{ID: "test-id", Res: r, Done: true}
33+
conn := &TestConn{}
34+
ctx := MethodContext{ID: "test-id", Conn: conn, Done: true}
3535
err := ctx.SendResult(100)
3636

3737
if err == nil {
3838
t.Error("result should be sent only once")
3939
}
4040

41-
if r._data != nil {
41+
if conn.out != nil {
4242
t.Error("result should be sent only once")
4343
}
4444
}
4545

4646
func TestSendError(t *testing.T) {
47-
r := &TestResponse{}
48-
ctx := MethodContext{ID: "test-id", Res: r}
47+
conn := &TestConn{}
48+
ctx := MethodContext{ID: "test-id", Conn: conn}
4949
err := ctx.SendError("test-error")
5050

5151
expected := map[string]interface{}{
@@ -64,28 +64,28 @@ func TestSendError(t *testing.T) {
6464
t.Error("context must set that a result is sent")
6565
}
6666

67-
if !reflect.DeepEqual(r._data, expected) {
67+
if !reflect.DeepEqual(conn.out, expected) {
6868
t.Error("invalid response for method error")
6969
}
7070
}
7171

7272
func TestSendErrorWhenDone(t *testing.T) {
73-
r := &TestResponse{}
74-
ctx := MethodContext{ID: "test-id", Res: r, Done: true}
73+
conn := &TestConn{}
74+
ctx := MethodContext{ID: "test-id", Conn: conn, Done: true}
7575
err := ctx.SendError("test-error")
7676

7777
if err == nil {
7878
t.Error("error should be sent only once")
7979
}
8080

81-
if r._data != nil {
81+
if conn.out != nil {
8282
t.Error("error should be sent only once")
8383
}
8484
}
8585

8686
func TestSendUpdated(t *testing.T) {
87-
r := &TestResponse{}
88-
ctx := MethodContext{ID: "test-id", Res: r}
87+
conn := &TestConn{}
88+
ctx := MethodContext{ID: "test-id", Conn: conn}
8989
err := ctx.SendUpdated()
9090

9191
expected := map[string]interface{}{
@@ -101,21 +101,21 @@ func TestSendUpdated(t *testing.T) {
101101
t.Error("context must set that updated is sent")
102102
}
103103

104-
if !reflect.DeepEqual(r._data, expected) {
104+
if !reflect.DeepEqual(conn.out, expected) {
105105
t.Error("invalid response for method updated")
106106
}
107107
}
108108

109109
func TestSendUpdatedWhenDone(t *testing.T) {
110-
r := &TestResponse{}
111-
ctx := MethodContext{ID: "test-id", Res: r, Updated: true}
110+
conn := &TestConn{}
111+
ctx := MethodContext{ID: "test-id", Conn: conn, Updated: true}
112112
err := ctx.SendUpdated()
113113

114114
if err == nil {
115115
t.Error("updated message should be sent only once")
116116
}
117117

118-
if r._data != nil {
118+
if conn.out != nil {
119119
t.Error("updated message should be sent only once")
120120
}
121121
}

server/server.go

Lines changed: 34 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package server
22

33
import (
4-
"errors"
54
"fmt"
65
"io"
76
"net/http"
@@ -10,83 +9,84 @@ import (
109
"golang.org/x/net/websocket"
1110
)
1211

12+
type Server struct {
13+
methods map[string]MethodHandler
14+
wsserver websocket.Server
15+
}
16+
1317
func New() Server {
1418
s := Server{}
15-
s.wsserver = websocket.Server{Handler: s.wsHandler, Handshake: handshake}
16-
s.methods = make(map[string]MethodFn)
19+
s.methods = make(map[string]MethodHandler)
20+
s.wsserver = websocket.Server{Handler: s.handler, Handshake: s.handshake}
1721
return s
1822
}
1923

20-
type Server struct {
21-
methods map[string]MethodFn
22-
wsserver websocket.Server
23-
}
24-
2524
func (s *Server) Listen(addr string) error {
2625
http.Handle("/websocket", s.wsserver)
2726
http.Handle("/sockjs/websocket", s.wsserver)
2827
return http.ListenAndServe(addr, nil)
2928
}
3029

31-
func (s *Server) Method(name string, fn MethodFn) {
30+
func (s *Server) Method(name string, fn MethodHandler) {
3231
s.methods[name] = fn
3332
}
3433

35-
func (s *Server) wsHandler(ws *websocket.Conn) {
34+
func (s *Server) handshake(config *websocket.Config, req *http.Request) error {
35+
// accept all connections
36+
return nil
37+
}
38+
39+
func (s *Server) handler(ws *websocket.Conn) {
40+
conn := Conn{ws}
41+
defer ws.Close()
42+
3643
for {
3744
var msg Message
38-
if err := websocket.JSON.Receive(ws, &msg); err != nil {
45+
if err := conn.ReadJSON(&msg); err != nil {
3946
if err != io.EOF {
40-
fmt.Println("Read Error: ", err)
47+
fmt.Println("Error (Read Error):", err, msg)
4148
}
4249

4350
break
4451
}
4552

4653
switch msg.Msg {
4754
case "connect":
48-
handleConnect(s, ws, msg)
55+
s.handleConnect(&conn, msg)
4956
case "ping":
50-
handlePing(s, ws, msg)
57+
s.handlePing(&conn, msg)
5158
case "method":
52-
handleMethod(s, ws, msg)
59+
s.handleMethod(&conn, msg)
5360
default:
54-
fmt.Println("Error: unknown message type", msg)
61+
fmt.Println("Error (Unknown Message Type):", msg)
5562
// TODO => send "error" ddp message
5663
break
5764
}
5865
}
59-
60-
ws.Close()
61-
}
62-
63-
func handshake(config *websocket.Config, req *http.Request) error {
64-
// accept all connections
65-
return nil
6666
}
6767

68-
func handleConnect(s *Server, ws *websocket.Conn, m Message) error {
69-
return websocket.JSON.Send(ws, map[string]string{
68+
func (s *Server) handleConnect(conn Connection, m Message) {
69+
msg := map[string]string{
7070
"msg": "connected",
7171
"session": random.Id(17),
72-
})
72+
}
73+
74+
conn.WriteJSON(msg)
7375
}
7476

75-
func handleMethod(s *Server, ws *websocket.Conn, m Message) error {
77+
func (s *Server) handleMethod(conn Connection, m Message) {
7678
fn, ok := s.methods[m.Method]
7779

7880
if !ok {
79-
err := errors.New(fmt.Sprintf("method %s not found", m.Method))
80-
return err
81+
fmt.Println("Error: (Method '%s' Not Found)", m.Method)
82+
return
8183
}
8284

83-
ctx := NewMethodContext(m, ws)
85+
ctx := NewMethodContext(m, conn)
8486
go fn(ctx)
85-
86-
return nil
8787
}
8888

89-
func handlePing(s *Server, ws *websocket.Conn, m Message) error {
89+
func (s *Server) handlePing(conn Connection, m Message) {
9090
msg := map[string]string{
9191
"msg": "pong",
9292
}
@@ -95,5 +95,5 @@ func handlePing(s *Server, ws *websocket.Conn, m Message) error {
9595
msg["id"] = m.ID
9696
}
9797

98-
return websocket.JSON.Send(ws, msg)
98+
conn.WriteJSON(msg)
9999
}

0 commit comments

Comments
 (0)