Skip to content

Commit f478a26

Browse files
refactor: remove message.Entry and introduce Message (#39)
1 parent 1ac862c commit f478a26

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+493
-647
lines changed

Makefile

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@ lint-fix:
1515
golangci-lint run --concurrency=2 --fix
1616

1717
test:
18-
CGO_ENABLED=1 go test -count=1 -race -covermode=atomic -coverprofile=.testCoverage.txt -timeout=2m . ./message
18+
CGO_ENABLED=1 go test -count=1 -race -covermode=atomic -coverprofile=.testCoverage.txt -timeout=2m .
1919

2020
test-v:
21-
CGO_ENABLED=1 go test -count=1 -race -covermode=atomic -coverprofile=.testCoverage.txt -timeout=2m -v . ./message
21+
CGO_ENABLED=1 go test -count=1 -race -covermode=atomic -coverprofile=.testCoverage.txt -timeout=2m -v .
2222

2323
cover-view:
2424
go tool cover -func .testCoverage.txt

README.md

Lines changed: 24 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -72,13 +72,10 @@ func main() {
7272
req := c.Request()
7373

7474
// do things...
75-
fmt.Printf("[server] request received | id: %d; size: %d; data: %s\n", req.ID, len(req.Data), req.Data)
75+
fmt.Printf("[server] request received | id: %d; size: %d; data: %s\n", req.ID(), len(req.Data()), req.Data())
7676

7777
// set response
78-
c.SetResponseMessage(&message.Entry{
79-
ID: 1002,
80-
Data: []byte("copy that"),
81-
})
78+
c.SetResponseMessage(easytcp.NewMessage(1002, []byte("copy that")))
8279
})
8380

8481
// Set custom logger (optional).
@@ -136,11 +133,11 @@ s.AddRoute(1001, func(c easytcp.Context) {
136133

137134
Above is the server side example. There are client and more detailed examples including:
138135

139-
- [broadcasting](./examples/tcp/broadcast)
140-
- [custom packet](./examples/tcp/custom_packet)
141-
- [communicating with protobuf](./examples/tcp/proto_packet)
136+
- [broadcasting](./internal/examples/tcp/broadcast)
137+
- [custom packet](./internal/examples/tcp/custom_packet)
138+
- [communicating with protobuf](./internal/examples/tcp/proto_packet)
142139

143-
in [examples/tcp](./examples/tcp).
140+
in [examples/tcp](./internal/examples/tcp).
144141

145142
## Benchmark
146143

@@ -150,10 +147,10 @@ goos: darwin
150147
goarch: amd64
151148
pkg: github.com/DarthPestilane/easytcp
152149
cpu: Intel(R) Core(TM) i5-8279U CPU @ 2.40GHz
153-
Benchmark_NoHandler-8 250000 4151 ns/op 81 B/op 2 allocs/op
154-
Benchmark_OneHandler-8 250000 4322 ns/op 82 B/op 2 allocs/op
155-
Benchmark_DefaultPacker_Pack-8 250000 36.37 ns/op 16 B/op 1 allocs/op
156-
Benchmark_DefaultPacker_Unpack-8 250000 110.1 ns/op 96 B/op 3 allocs/op
150+
Benchmark_NoHandler-8 250000 4667 ns/op 84 B/op 2 allocs/op
151+
Benchmark_OneHandler-8 250000 4351 ns/op 82 B/op 2 allocs/op
152+
Benchmark_DefaultPacker_Pack-8 250000 33.57 ns/op 16 B/op 1 allocs/op
153+
Benchmark_DefaultPacker_Unpack-8 250000 104.4 ns/op 96 B/op 3 allocs/op
157154
```
158155

159156
*since easytcp is built on the top of golang `net` library, the benchmark of networks does not make much sense.*
@@ -219,13 +216,10 @@ s.AddRoute(reqID, func(c easytcp.Context) {
219216
req := c.Request()
220217

221218
// do things...
222-
fmt.Printf("[server] request received | id: %d; size: %d; data: %s\n", req.ID, len(req.Data), req.Data)
219+
fmt.Printf("[server] request received | id: %d; size: %d; data: %s\n", req.ID(), len(req.Data()), req.Data())
223220

224221
// set response
225-
c.SetResponseMessage(&message.Entry{
226-
ID: respID,
227-
Data: []byte("copy that"),
228-
})
222+
c.SetResponseMessage(easytcp.NewMessage(respID, []byte("copy that")))
229223
})
230224
```
231225

@@ -261,7 +255,7 @@ s := easytcp.NewServer(&easytcp.ServerOption{
261255

262256
We can set our own Packer or EasyTCP uses [`DefaultPacker`](./packer.go).
263257

264-
The `DefaultPacker` considers packet's payload as a `Size(4)|ID(4)|Data(n)` format. (`Size` only represents the length of `Data` instead of the whole payload length)
258+
The `DefaultPacker` considers packet's payload as a `Size(4)|ID(4)|Data(n)` format. **`Size` only represents the length of `Data` instead of the whole payload length**
265259

266260
This may not covery some particular cases, but fortunately, we can create our own Packer.
267261

@@ -274,16 +268,16 @@ func (p *CustomPacker) bytesOrder() binary.ByteOrder {
274268
return binary.BigEndian
275269
}
276270

277-
func (p *CustomPacker) Pack(entry *message.Entry) ([]byte, error) {
278-
size := len(entry.Data) // only the size of data.
271+
func (p *CustomPacker) Pack(msg *easytcp.Message) ([]byte, error) {
272+
size := len(msg.Data()) // only the size of data.
279273
buffer := make([]byte, 2+2+size)
280274
p.bytesOrder().PutUint16(buffer[:2], uint16(size))
281-
p.bytesOrder().PutUint16(buffer[2:4], entry.ID.(uint16))
282-
copy(buffer[4:], entry.Data)
275+
p.bytesOrder().PutUint16(buffer[2:4], msg.ID().(uint16))
276+
copy(buffer[4:], msg.Data())
283277
return buffer, nil
284278
}
285279

286-
func (p *CustomPacker) Unpack(reader io.Reader) (*message.Entry, error) {
280+
func (p *CustomPacker) Unpack(reader io.Reader) (*easytcp.Message, error) {
287281
headerBuffer := make([]byte, 2+2)
288282
if _, err := io.ReadFull(reader, headerBuffer); err != nil {
289283
return nil, fmt.Errorf("read size and id err: %s", err)
@@ -296,15 +290,12 @@ func (p *CustomPacker) Unpack(reader io.Reader) (*message.Entry, error) {
296290
return nil, fmt.Errorf("read data err: %s", err)
297291
}
298292

299-
entry := &message.Entry{
300-
// since entry.ID is type of uint16, we need to use uint16 as well when adding routes.
301-
// eg: server.AddRoute(uint16(123), ...)
302-
ID: id,
303-
Data: data,
304-
}
305-
entry.Set("theWholeLength", 2+2+size) // we can set our custom kv data here.
293+
// since msg.ID is type of uint16, we need to use uint16 as well when adding routes.
294+
// eg: server.AddRoute(uint16(123), ...)
295+
msg := easytcp.NewMessage(id, data)
296+
msg.Set("theWholeLength", 2+2+size) // we can set our custom kv data here.
306297
// c.Request().Get("theWholeLength") // and get them in route handler.
307-
return entry, nil
298+
return msg, nil
308299
}
309300
```
310301

@@ -333,7 +324,7 @@ s.AddRoute(reqID, func(c easytcp.Context) {
333324
// handle error...
334325
}
335326
req := c.Request()
336-
fmt.Printf("[server] request received | id: %d; size: %d; data-decoded: %+v\n", req.ID, len(req.Data), reqData)
327+
fmt.Printf("[server] request received | id: %d; size: %d; data-decoded: %+v\n", req.ID(), len(req.Data()), reqData())
337328
respData := map[string]string{"key": "value"}
338329
if err := c.SetResponse(respID, respData); err != nil {
339330
// handle error...

benchmarks_test.go

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package easytcp
22

33
import (
44
"bytes"
5-
"github.com/DarthPestilane/easytcp/message"
65
"github.com/stretchr/testify/assert"
76
"io"
87
"net"
@@ -32,10 +31,10 @@ func Benchmark_NoHandler(b *testing.B) {
3231
}
3332
defer client.Close() // nolint
3433

35-
packedMsg, _ := s.Packer.Pack(&message.Entry{ID: 1, Data: []byte("ping")})
34+
packedBytes, _ := s.Packer.Pack(NewMessage(1, []byte("ping")))
3635
beforeBench(b)
3736
for i := 0; i < b.N; i++ {
38-
_, _ = client.Write(packedMsg)
37+
_, _ = client.Write(packedBytes)
3938
}
4039
}
4140

@@ -56,7 +55,7 @@ func Benchmark_OneHandler(b *testing.B) {
5655
}
5756
defer client.Close() // nolint
5857

59-
packedMsg, _ := s.Packer.Pack(&message.Entry{ID: 1, Data: []byte("ping")})
58+
packedMsg, _ := s.Packer.Pack(NewMessage(1, []byte("ping")))
6059
beforeBench(b)
6160
for i := 0; i < b.N; i++ {
6261
_, _ = client.Write(packedMsg)
@@ -65,11 +64,7 @@ func Benchmark_OneHandler(b *testing.B) {
6564

6665
func Benchmark_DefaultPacker_Pack(b *testing.B) {
6766
packer := NewDefaultPacker()
68-
69-
msg := &message.Entry{
70-
ID: 1,
71-
Data: []byte("test"),
72-
}
67+
msg := NewMessage(1, []byte("test"))
7368
beforeBench(b)
7469
for i := 0; i < b.N; i++ {
7570
_, _ = packer.Pack(msg)
@@ -78,10 +73,7 @@ func Benchmark_DefaultPacker_Pack(b *testing.B) {
7873

7974
func Benchmark_DefaultPacker_Unpack(b *testing.B) {
8075
packer := NewDefaultPacker()
81-
msg := &message.Entry{
82-
ID: 1,
83-
Data: []byte("test"),
84-
}
76+
msg := NewMessage(1, []byte("test"))
8577
dataBytes, err := packer.Pack(msg)
8678
assert.NoError(b, err)
8779

examples/tcp/custom_packet/common/packer_test.go

Lines changed: 0 additions & 27 deletions
This file was deleted.

examples/tcp/proto_packet/common/packer_test.go

Lines changed: 0 additions & 27 deletions
This file was deleted.

examples/tcp/simple/client/main.go

Lines changed: 0 additions & 50 deletions
This file was deleted.
File renamed without changes.

examples/tcp/broadcast/client/main.go renamed to internal/examples/tcp/broadcast/client/main.go

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,8 @@ package main
33
import (
44
"fmt"
55
"github.com/DarthPestilane/easytcp"
6-
"github.com/DarthPestilane/easytcp/examples/fixture"
7-
"github.com/DarthPestilane/easytcp/examples/tcp/broadcast/common"
8-
"github.com/DarthPestilane/easytcp/message"
6+
"github.com/DarthPestilane/easytcp/internal/examples/fixture"
7+
"github.com/DarthPestilane/easytcp/internal/examples/tcp/broadcast/common"
98
"github.com/sirupsen/logrus"
109
"net"
1110
"time"
@@ -44,12 +43,7 @@ func senderClient() {
4443
for {
4544
time.Sleep(time.Second)
4645
data := []byte(fmt.Sprintf("hello everyone @%d", time.Now().Unix()))
47-
msg := &message.Entry{
48-
ID: common.MsgIdBroadCastReq,
49-
Data: data,
50-
}
51-
52-
packedMsg, _ := packer.Pack(msg)
46+
packedMsg, _ := packer.Pack(easytcp.NewMessage(common.MsgIdBroadCastReq, data))
5347
if _, err := conn.Write(packedMsg); err != nil {
5448
log.Error(err)
5549
return

examples/tcp/broadcast/server/main.go renamed to internal/examples/tcp/broadcast/server/main.go

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,8 @@ package main
33
import (
44
"fmt"
55
"github.com/DarthPestilane/easytcp"
6-
"github.com/DarthPestilane/easytcp/examples/fixture"
7-
"github.com/DarthPestilane/easytcp/examples/tcp/broadcast/common"
8-
"github.com/DarthPestilane/easytcp/message"
6+
fixture2 "github.com/DarthPestilane/easytcp/internal/examples/fixture"
7+
"github.com/DarthPestilane/easytcp/internal/examples/tcp/broadcast/common"
98
"github.com/sirupsen/logrus"
109
"os"
1110
"os/signal"
@@ -47,7 +46,7 @@ func main() {
4746
delete(sessions.storage, sess.ID().(int64))
4847
}
4948

50-
s.Use(fixture.RecoverMiddleware(log), logMiddleware)
49+
s.Use(fixture2.RecoverMiddleware(log), logMiddleware)
5150

5251
s.AddRoute(common.MsgIdBroadCastReq, func(ctx easytcp.Context) {
5352
reqData := ctx.Request().Data
@@ -60,24 +59,21 @@ func main() {
6059
continue
6160
}
6261
respData := fmt.Sprintf("%s (broadcast from %d to %d)", reqData, currentSession.ID(), targetSession.ID())
63-
respEntry := &message.Entry{ID: common.MsgIdBroadCastAck, Data: []byte(respData)}
62+
respMsg := easytcp.NewMessage(common.MsgIdBroadCastAck, []byte(respData))
6463
go func() {
65-
targetSession.AllocateContext().SetResponseMessage(respEntry).Send()
64+
targetSession.AllocateContext().SetResponseMessage(respMsg).Send()
6665
// can also write like this.
67-
// ctx.Copy().SetResponseMessage(respEntry).SendTo(targetSession)
66+
// ctx.Copy().SetResponseMessage(respMsg).SendTo(targetSession)
6867
// or this.
69-
// ctx.Copy().SetSession(targetSession).SetResponseMessage(respEntry).Send()
68+
// ctx.Copy().SetSession(targetSession).SetResponseMessage(respMsg).Send()
7069
}()
7170
}
7271

73-
ctx.SetResponseMessage(&message.Entry{
74-
ID: common.MsgIdBroadCastAck,
75-
Data: []byte("broadcast done"),
76-
})
72+
ctx.SetResponseMessage(easytcp.NewMessage(common.MsgIdBroadCastAck, []byte("broadcast done")))
7773
})
7874

7975
go func() {
80-
if err := s.Serve(fixture.ServerAddr); err != nil {
76+
if err := s.Serve(fixture2.ServerAddr); err != nil {
8177
log.Error(err)
8278
}
8379
}()
@@ -95,8 +91,8 @@ func logMiddleware(next easytcp.HandlerFunc) easytcp.HandlerFunc {
9591
return func(ctx easytcp.Context) {
9692
log.Infof("recv request | %s", ctx.Request().Data)
9793
defer func() {
98-
var resp = ctx.Response()
99-
log.Infof("send response |sessId: %d; id: %d; size: %d; data: %s", ctx.Session().ID(), resp.ID, len(resp.Data), resp.Data)
94+
var respMsg = ctx.Response()
95+
log.Infof("send response |sessId: %d; id: %d; size: %d; data: %s", ctx.Session().ID(), respMsg.ID(), len(respMsg.Data()), respMsg.Data())
10096
}()
10197
next(ctx)
10298
}

0 commit comments

Comments
 (0)