conn.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2018 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 net
  15. import (
  16. "bytes"
  17. "io"
  18. "net"
  19. )
  20. type SharedConn struct {
  21. net.Conn
  22. buf *bytes.Buffer
  23. }
  24. // the bytes you read in io.Reader, will be reserved in SharedConn
  25. func NewSharedConn(conn net.Conn) (*SharedConn, io.Reader) {
  26. sc := &SharedConn{
  27. Conn: conn,
  28. buf: bytes.NewBuffer(make([]byte, 0, 1024)),
  29. }
  30. return sc, io.TeeReader(conn, sc.buf)
  31. }
  32. func NewSharedConnSize(conn net.Conn, bufSize int) (*SharedConn, io.Reader) {
  33. sc := &SharedConn{
  34. Conn: conn,
  35. buf: bytes.NewBuffer(make([]byte, 0, bufSize)),
  36. }
  37. return sc, io.TeeReader(conn, sc.buf)
  38. }
  39. // Not thread safety.
  40. func (sc *SharedConn) Read(p []byte) (n int, err error) {
  41. if sc.buf == nil {
  42. return sc.Conn.Read(p)
  43. }
  44. n, err = sc.buf.Read(p)
  45. if err == io.EOF {
  46. sc.buf = nil
  47. var n2 int
  48. n2, err = sc.Conn.Read(p[n:])
  49. n += n2
  50. }
  51. return
  52. }
  53. func (sc *SharedConn) ResetBuf(buffer []byte) (err error) {
  54. sc.buf.Reset()
  55. _, err = sc.buf.Write(buffer)
  56. return err
  57. }