utils_io.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package utils
  7. import (
  8. "io"
  9. )
  10. // ReadCloser implements the io.ReadCloser interface
  11. // which is used for reading request body content multiple times.
  12. //
  13. // Note that it cannot be closed.
  14. type ReadCloser struct {
  15. index int // Current read position.
  16. content []byte // Content.
  17. repeatable bool // Mark the content can be repeatable read.
  18. }
  19. // NewReadCloser creates and returns a RepeatReadCloser object.
  20. func NewReadCloser(content []byte, repeatable bool) io.ReadCloser {
  21. return &ReadCloser{
  22. content: content,
  23. repeatable: repeatable,
  24. }
  25. }
  26. // Read implements the io.ReadCloser interface.
  27. func (b *ReadCloser) Read(p []byte) (n int, err error) {
  28. // Make it repeatable reading.
  29. if b.index >= len(b.content) && b.repeatable {
  30. b.index = 0
  31. }
  32. n = copy(p, b.content[b.index:])
  33. b.index += n
  34. if b.index >= len(b.content) {
  35. return n, io.EOF
  36. }
  37. return n, nil
  38. }
  39. // Close implements the io.ReadCloser interface.
  40. func (b *ReadCloser) Close() error {
  41. return nil
  42. }