You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

stats.go 1.2 kB

9 months ago
9 months ago
9 months ago
9 months ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package io2
  2. import "io"
  3. type counter struct {
  4. inner io.Reader
  5. count int64
  6. }
  7. func (c *counter) Read(buf []byte) (n int, err error) {
  8. n, err = c.inner.Read(buf)
  9. c.count += int64(n)
  10. return
  11. }
  12. func (c *counter) Count() int64 {
  13. return c.count
  14. }
  15. func Counter(inner io.Reader) *counter {
  16. return &counter{inner: inner, count: 0}
  17. }
  18. type counterCloser struct {
  19. inner io.ReadCloser
  20. count int64
  21. callback func(cnt int64, err error)
  22. }
  23. func (c *counterCloser) Read(buf []byte) (n int, err error) {
  24. n, err = c.inner.Read(buf)
  25. c.count += int64(n)
  26. if err != nil && c.callback != nil {
  27. c.callback(c.count, err)
  28. c.callback = nil
  29. }
  30. return
  31. }
  32. func (c *counterCloser) Close() error {
  33. // 读取方主动Close,视为正常结束
  34. err := c.inner.Close()
  35. if c.callback != nil {
  36. c.callback(c.count, nil)
  37. }
  38. return err
  39. }
  40. // 统计一个io.ReadCloser的读取字节数,在读取结束后调用callback函数。
  41. // 仅在读取方主动调用Close时,callback的err参数才会为nil。
  42. func CounterCloser(inner io.ReadCloser, callback func(cnt int64, err error)) io.ReadCloser {
  43. return &counterCloser{inner: inner, count: 0, callback: callback}
  44. }