-
-
Notifications
You must be signed in to change notification settings - Fork 13.3k
/
rpc.go
38 lines (34 loc) · 744 Bytes
/
rpc.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
package rpc
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
)
func WriteBytes(w io.Writer, buf []byte) (int, error) {
out := bytes.NewBuffer(nil)
if err := binary.Write(out, binary.BigEndian, int64(len(buf))); err != nil {
return 0, err
}
out.Write(buf)
return w.Write(out.Bytes())
}
func ReadBytes(r io.Reader) ([]byte, error) {
var length int64
if err := binary.Read(r, binary.BigEndian, &length); err != nil {
return nil, err
}
if length < 0 || length > 10*1024*1024 {
return nil, fmt.Errorf("invalid length")
}
buffer := make([]byte, length)
n, err := io.ReadFull(r, buffer)
if err != nil {
return nil, err
}
if int64(n) != length {
return nil, errors.New("invalid length")
}
return buffer, nil
}