-
Notifications
You must be signed in to change notification settings - Fork 3
/
framer.go
100 lines (82 loc) · 1.77 KB
/
framer.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
98
99
100
package main
import (
"bytes"
"fmt"
"io"
"golang.org/x/net/http2"
"golang.org/x/net/http2/hpack"
)
const frameHeaderLen = 9
type Framer struct {
writeBuf *bytes.Buffer
readBuf *bytes.Buffer
chunkBuf []byte
framer *http2.Framer
decoder *hpack.Decoder
hfCallback func(hpack.HeaderField)
preface bool
}
func (f *Framer) ReadFrame(chunk []byte, callback func(http2.Frame) error) {
if !f.preface {
if string(chunk[:24]) == "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" {
f.preface = true
chunk = chunk[24:]
}
}
available := false
chunk = append(f.chunkBuf, chunk...)
for {
cLen := len(chunk)
if cLen < frameHeaderLen {
break
}
pLen := int(uint32(chunk[0])<<16 | uint32(chunk[1])<<8 | uint32(chunk[2]))
pEnd := (frameHeaderLen + pLen)
if cLen < pEnd {
break
}
f.readBuf.Write(chunk[:pEnd])
chunk = chunk[pEnd:]
available = true
}
f.chunkBuf = chunk
if !available {
return
}
for {
frame, err := f.framer.ReadFrame()
if err != nil {
if err != io.EOF {
fmt.Printf("Read frame error: %s", err)
}
break
} else {
callback(frame)
}
}
}
func (f *Framer) ReadHeader(chunk []byte, callback func(hpack.HeaderField)) {
f.hfCallback = callback
f.decoder.Write(chunk)
f.hfCallback = nil
}
func (f *Framer) SetMaxDynamicTableSize(size uint32) {
f.decoder.SetMaxDynamicTableSize(size)
}
func NewFramer(remote bool) *Framer {
writeBuf := bytes.NewBuffer(make([]byte, 0))
readBuf := bytes.NewBuffer(make([]byte, 0))
framer := &Framer{
writeBuf: writeBuf,
readBuf: readBuf,
chunkBuf: []byte{},
framer: http2.NewFramer(writeBuf, readBuf),
preface: !remote,
}
framer.decoder = hpack.NewDecoder(4096, func(hf hpack.HeaderField) {
if framer.hfCallback != nil {
framer.hfCallback(hf)
}
})
return framer
}