frp/test/e2e/pkg/rpc/rpc.go

39 lines
744 B
Go
Raw Normal View History

package rpc
import (
"bytes"
"encoding/binary"
"errors"
2023-03-07 12:53:32 +01:00
"fmt"
"io"
)
func WriteBytes(w io.Writer, buf []byte) (int, error) {
out := bytes.NewBuffer(nil)
2022-08-28 19:02:53 +02:00
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
2021-06-21 13:27:26 +02:00
if err := binary.Read(r, binary.BigEndian, &length); err != nil {
return nil, err
}
2023-03-07 12:53:32 +01:00
if length < 0 || length > 10*1024*1024 {
return nil, fmt.Errorf("invalid length")
}
buffer := make([]byte, length)
2021-06-21 13:27:26 +02:00
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
}