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

feat: add ReadFile

This commit is contained in:
dudaodong
2023-09-24 19:19:09 +08:00
parent 561c42a24e
commit f37e55d9f1
4 changed files with 124 additions and 2 deletions

View File

@@ -19,10 +19,11 @@ import (
"io/ioutil"
"net/http"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"github.com/duke-git/lancet/validator"
)
// IsExist checks if a file or directory exists
@@ -449,7 +450,7 @@ func CurrentPath() string {
var absPath string
_, filename, _, ok := runtime.Caller(1)
if ok {
absPath = path.Dir(filename)
absPath = filepath.Dir(filename)
}
return absPath
@@ -589,3 +590,23 @@ func WriteBytesToFile(filepath string, content []byte) error {
_, err = f.Write(content)
return err
}
// ReadFile get file reader by a url or a local file.
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")
}
}