utils_io.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. "io/ioutil"
  10. "github.com/gogf/gf/v2/errors/gerror"
  11. )
  12. // ReadCloser implements the io.ReadCloser interface
  13. // which is used for reading request body content multiple times.
  14. //
  15. // Note that it cannot be closed.
  16. type ReadCloser struct {
  17. index int // Current read position.
  18. content []byte // Content.
  19. repeatable bool
  20. }
  21. // NewReadCloser creates and returns a RepeatReadCloser object.
  22. func NewReadCloser(content []byte, repeatable bool) io.ReadCloser {
  23. return &ReadCloser{
  24. content: content,
  25. repeatable: repeatable,
  26. }
  27. }
  28. // NewReadCloserWithReadCloser creates and returns a RepeatReadCloser object
  29. // with given io.ReadCloser.
  30. func NewReadCloserWithReadCloser(r io.ReadCloser, repeatable bool) (io.ReadCloser, error) {
  31. content, err := ioutil.ReadAll(r)
  32. if err != nil {
  33. err = gerror.Wrapf(err, `ioutil.ReadAll failed`)
  34. return nil, err
  35. }
  36. defer r.Close()
  37. return &ReadCloser{
  38. content: content,
  39. repeatable: repeatable,
  40. }, nil
  41. }
  42. // Read implements the io.ReadCloser interface.
  43. func (b *ReadCloser) Read(p []byte) (n int, err error) {
  44. n = copy(p, b.content[b.index:])
  45. b.index += n
  46. if b.index >= len(b.content) {
  47. // Make it repeatable reading.
  48. if b.repeatable {
  49. b.index = 0
  50. }
  51. return n, io.EOF
  52. }
  53. return n, nil
  54. }
  55. // Close implements the io.ReadCloser interface.
  56. func (b *ReadCloser) Close() error {
  57. return nil
  58. }