-
Notifications
You must be signed in to change notification settings - Fork 51
/
net.go
97 lines (76 loc) · 1.69 KB
/
net.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
85
86
87
88
89
90
91
92
93
94
95
96
97
package flatend
import (
"github.com/lithdew/kademlia"
"github.com/lithdew/monte"
"io"
"sync"
)
const ChunkSize = 2048
var _ io.Writer = (*Context)(nil)
type Context struct {
ID kademlia.ID
Headers map[string]string
Body io.ReadCloser
nonce uint32 // stream id
conn *monte.Conn
headers map[string]string // response headers
written bool // written before?
}
func (c *Context) WriteHeader(key, val string) {
c.headers[key] = val
}
func (c *Context) Write(data []byte) (int, error) {
if len(data) == 0 { // disallow writing zero bytes
return 0, nil
}
if !c.written {
packet := ServiceResponsePacket{
ID: c.nonce,
Handled: true,
Headers: c.headers,
}
c.written = true
err := c.conn.Send(packet.AppendTo([]byte{OpcodeServiceResponse}))
if err != nil {
return 0, err
}
}
for i := 0; i < len(data); i += ChunkSize {
start := i
end := i + ChunkSize
if end > len(data) {
end = len(data)
}
packet := DataPacket{
ID: c.nonce,
Data: data[start:end],
}
err := c.conn.Send(packet.AppendTo([]byte{OpcodeData}))
if err != nil {
return 0, err
}
}
return len(data), nil
}
var contextPool sync.Pool
func acquireContext(id kademlia.ID, headers map[string]string, body io.ReadCloser, nonce uint32, conn *monte.Conn) *Context {
v := contextPool.Get()
if v == nil {
v = &Context{headers: make(map[string]string)}
}
ctx := v.(*Context)
ctx.ID = id
ctx.Headers = headers
ctx.Body = body
ctx.nonce = nonce
ctx.conn = conn
return ctx
}
func releaseContext(ctx *Context) {
ctx.written = false
for key := range ctx.headers {
delete(ctx.headers, key)
}
contextPool.Put(ctx)
}
type Handler func(ctx *Context)