functions.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package proxy
  2. import (
  3. "io"
  4. "log"
  5. "net"
  6. "runtime/debug"
  7. "sync"
  8. "time"
  9. )
  10. func ConnectHost(hostAndPort string, timeout int) (conn net.Conn, err error) {
  11. conn, err = net.DialTimeout("tcp", hostAndPort, time.Duration(timeout)*time.Millisecond)
  12. return
  13. }
  14. func CloseConn(conn *net.Conn) {
  15. if conn != nil && *conn != nil {
  16. _ = (*conn).SetDeadline(time.Now().Add(time.Millisecond))
  17. _ = (*conn).Close()
  18. }
  19. }
  20. func IoBind(dst io.ReadWriter, src io.ReadWriter, fn func(isSrcErr bool, err error), cfn func(count int, isPositive bool), bytesPreSec float64) {
  21. var one = &sync.Once{}
  22. go func() {
  23. defer func() {
  24. if e := recover(); e != nil {
  25. log.Printf("IoBind crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
  26. }
  27. }()
  28. var err error
  29. var isSrcErr bool
  30. if bytesPreSec > 0 {
  31. newReader := NewReader(src)
  32. newReader.SetRateLimit(bytesPreSec)
  33. _, isSrcErr, err = IoCopy(dst, newReader, func(c int) {
  34. cfn(c, false)
  35. })
  36. } else {
  37. _, isSrcErr, err = IoCopy(dst, src, func(c int) {
  38. cfn(c, false)
  39. })
  40. }
  41. if err != nil {
  42. one.Do(func() {
  43. fn(isSrcErr, err)
  44. })
  45. }
  46. }()
  47. go func() {
  48. defer func() {
  49. if e := recover(); e != nil {
  50. log.Printf("IoBind crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
  51. }
  52. }()
  53. var err error
  54. var isSrcErr bool
  55. if bytesPreSec > 0 {
  56. newReader := NewReader(dst)
  57. newReader.SetRateLimit(bytesPreSec)
  58. _, isSrcErr, err = IoCopy(src, newReader, func(c int) {
  59. cfn(c, true)
  60. })
  61. } else {
  62. _, isSrcErr, err = IoCopy(src, dst, func(c int) {
  63. cfn(c, true)
  64. })
  65. }
  66. if err != nil {
  67. one.Do(func() {
  68. fn(isSrcErr, err)
  69. })
  70. }
  71. }()
  72. }
  73. func IoCopy(dst io.Writer, src io.Reader, fn ...func(count int)) (written int64, isSrcErr bool, err error) {
  74. buf := make([]byte, 32*1024)
  75. for {
  76. nr, er := src.Read(buf)
  77. if nr > 0 {
  78. nw, ew := dst.Write(buf[0:nr])
  79. if nw > 0 {
  80. written += int64(nw)
  81. if len(fn) == 1 {
  82. fn[0](nw)
  83. }
  84. }
  85. if ew != nil {
  86. err = ew
  87. break
  88. }
  89. if nr != nw {
  90. err = io.ErrShortWrite
  91. break
  92. }
  93. }
  94. if er != nil {
  95. err = er
  96. isSrcErr = true
  97. break
  98. }
  99. }
  100. return written, isSrcErr, err
  101. }