github.com/wangyougui/gf/v2@v2.6.5/internal/utils/utils_io.go (about)

     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/wangyougui/gf.
     6  
     7  package utils
     8  
     9  import (
    10  	"io"
    11  )
    12  
    13  // ReadCloser implements the io.ReadCloser interface
    14  // which is used for reading request body content multiple times.
    15  //
    16  // Note that it cannot be closed.
    17  type ReadCloser struct {
    18  	index      int    // Current read position.
    19  	content    []byte // Content.
    20  	repeatable bool   // Mark the content can be repeatable read.
    21  }
    22  
    23  // NewReadCloser creates and returns a RepeatReadCloser object.
    24  func NewReadCloser(content []byte, repeatable bool) io.ReadCloser {
    25  	return &ReadCloser{
    26  		content:    content,
    27  		repeatable: repeatable,
    28  	}
    29  }
    30  
    31  // Read implements the io.ReadCloser interface.
    32  func (b *ReadCloser) Read(p []byte) (n int, err error) {
    33  	// Make it repeatable reading.
    34  	if b.index >= len(b.content) && b.repeatable {
    35  		b.index = 0
    36  	}
    37  	n = copy(p, b.content[b.index:])
    38  	b.index += n
    39  	if b.index >= len(b.content) {
    40  		return n, io.EOF
    41  	}
    42  	return n, nil
    43  }
    44  
    45  // Close implements the io.ReadCloser interface.
    46  func (b *ReadCloser) Close() error {
    47  	return nil
    48  }