1
0

rpc.go 744 B

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