gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/utils/io/read.go (about)

     1  package io
     2  
     3  import (
     4  	"errors"
     5  	"io"
     6  )
     7  
     8  var ErrLimit = errors.New("read reached limit")
     9  
    10  func ReadAllLimit(r io.Reader, limit int) ([]byte, error) {
    11  	b := make([]byte, 0, 512)
    12  	for {
    13  		if len(b) == cap(b) {
    14  			// Add more capacity (let append pick how much).
    15  			b = append(b, 0)[:len(b)]
    16  		}
    17  		c := limit
    18  		if c > cap(b) {
    19  			c = cap(b)
    20  		}
    21  		n, err := r.Read(b[len(b):c])
    22  		b = b[:len(b)+n]
    23  		if err != nil {
    24  			if err == io.EOF {
    25  				err = nil
    26  			}
    27  			return b, err
    28  		}
    29  		if len(b) == limit {
    30  			return b, ErrLimit
    31  		}
    32  	}
    33  }