1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-11 08:12:26 +08:00

feat(fileutil): add ReadFile func (#140)

This commit is contained in:
o98k
2023-09-23 13:45:02 +08:00
committed by GitHub
parent 073c77e751
commit 781b89d51a
5 changed files with 138 additions and 0 deletions

View File

@@ -22,6 +22,8 @@ import (
"path/filepath"
"runtime"
"strings"
"github.com/duke-git/lancet/v2/validator"
)
// IsExist checks if a file or directory exists.
@@ -624,3 +626,24 @@ func WriteBytesToFile(filepath string, content []byte) error {
_, err = f.Write(content)
return err
}
// ReadFile get file reader by a url or a local file
// Play: todo
func ReadFile(path string) (reader io.ReadCloser, closeFn func(), err error) {
switch {
case validator.IsUrl(path):
resp, err := http.Get(path)
if err != nil {
return nil, func() {}, err
}
return resp.Body, func() { resp.Body.Close() }, nil
case IsExist(path):
reader, err := os.Open(path)
if err != nil {
return nil, func() {}, err
}
return reader, func() { reader.Close() }, nil
default:
return nil, func() {}, errors.New("unknown file type")
}
}