rpc.go 605 B

12345678910111213141516171819202122232425262728293031
  1. package rpc
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "errors"
  6. "io"
  7. )
  8. func WriteBytes(w io.Writer, buf []byte) (int, error) {
  9. out := bytes.NewBuffer(nil)
  10. binary.Write(out, binary.BigEndian, int64(len(buf)))
  11. out.Write(buf)
  12. return w.Write(out.Bytes())
  13. }
  14. func ReadBytes(r io.Reader) ([]byte, error) {
  15. var length int64
  16. if err := binary.Read(r, binary.BigEndian, &length); err != nil {
  17. return nil, err
  18. }
  19. buffer := make([]byte, length)
  20. n, err := io.ReadFull(r, buffer)
  21. if err != nil {
  22. return nil, err
  23. }
  24. if int64(n) != length {
  25. return nil, errors.New("invalid length")
  26. }
  27. return buffer, nil
  28. }