38 lines
929 B
Go
38 lines
929 B
Go
package fileops
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"math"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
// ReadFileBounded reads at most limit bytes from path using ordinary workspace
|
|
// path semantics. It does not return partial data when the limit is exceeded.
|
|
func ReadFileBounded(path string, limit int64) ([]byte, error) {
|
|
if strings.TrimSpace(path) == "" {
|
|
return nil, fmt.Errorf("file path is required")
|
|
}
|
|
if limit < 0 {
|
|
return nil, fmt.Errorf("file read limit %d is invalid", limit)
|
|
}
|
|
file, err := os.Open(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open file %q: %w", path, err)
|
|
}
|
|
defer func() { _ = file.Close() }()
|
|
readLimit := limit
|
|
if limit < math.MaxInt64 {
|
|
readLimit++
|
|
}
|
|
data, err := io.ReadAll(io.LimitReader(file, readLimit))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read file %q: %w", path, err)
|
|
}
|
|
if int64(len(data)) > limit {
|
|
return nil, fmt.Errorf("file %q exceeds %d-byte limit", path, limit)
|
|
}
|
|
return data, nil
|
|
}
|