process.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2016 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package msg
  15. import (
  16. "encoding/binary"
  17. "fmt"
  18. "io"
  19. )
  20. var (
  21. MaxMsgLength int64 = 10240
  22. )
  23. func readMsg(c io.Reader) (typeByte byte, buffer []byte, err error) {
  24. buffer = make([]byte, 1)
  25. _, err = c.Read(buffer)
  26. if err != nil {
  27. return
  28. }
  29. typeByte = buffer[0]
  30. if _, ok := TypeMap[typeByte]; !ok {
  31. err = fmt.Errorf("Message type error")
  32. return
  33. }
  34. var length int64
  35. err = binary.Read(c, binary.BigEndian, &length)
  36. if err != nil {
  37. return
  38. }
  39. if length > MaxMsgLength {
  40. err = fmt.Errorf("Message length exceed the limit")
  41. return
  42. }
  43. buffer = make([]byte, length)
  44. n, err := io.ReadFull(c, buffer)
  45. if err != nil {
  46. return
  47. }
  48. if int64(n) != length {
  49. err = fmt.Errorf("Message format error")
  50. }
  51. return
  52. }
  53. func ReadMsg(c io.Reader) (msg Message, err error) {
  54. typeByte, buffer, err := readMsg(c)
  55. if err != nil {
  56. return
  57. }
  58. return UnPack(typeByte, buffer)
  59. }
  60. func ReadMsgInto(c io.Reader, msg Message) (err error) {
  61. _, buffer, err := readMsg(c)
  62. if err != nil {
  63. return
  64. }
  65. return UnPackInto(buffer, msg)
  66. }
  67. func WriteMsg(c io.Writer, msg interface{}) (err error) {
  68. buffer, err := Pack(msg)
  69. if err != nil {
  70. return
  71. }
  72. if _, err = c.Write(buffer); err != nil {
  73. return
  74. }
  75. return nil
  76. }