Skip to content

Commit

Permalink
URL: add FileProvider, use []byte for internal
Browse files Browse the repository at this point in the history
  • Loading branch information
tliron committed Jun 16, 2022
1 parent f708c20 commit 185513f
Show file tree
Hide file tree
Showing 5 changed files with 444 additions and 22 deletions.
17 changes: 17 additions & 0 deletions url/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package url

import (
"io"
neturl "net/url"
"os"

"github.com/tliron/kutil/ard"
Expand All @@ -11,6 +12,22 @@ import (

var log = logging.GetLogger("kutil.url")

func ToNetURL(url URL) (*neturl.URL, error) {
return neturl.ParseRequestURI(url.String())
}

func GetPath(url URL) (string, error) {
if url_, err := ToNetURL(url); err == nil {
if url_.Path != "" {
return neturl.PathUnescape(url_.Path)
} else {
return neturl.PathUnescape(url_.Opaque)
}
} else {
return "", err
}
}

func ReadBytes(url URL) ([]byte, error) {
if reader, err := url.Open(); err == nil {
defer reader.Close()
Expand Down
32 changes: 22 additions & 10 deletions url/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,19 @@ func (self *Context) GetCredentials(host string) *Credentials {
}
}

func (self *Context) Open(url URL) (*os.File, error) {
func (self *Context) OpenFile(url URL) (*os.File, error) {
if path, err := self.GetLocalPath(url); err == nil {
return os.Open(path)
} else {
return nil, err
}
}

// Will download the file to the local temporary directory if not already locally available
func (self *Context) GetLocalPath(url URL) (string, error) {
if fileUrl, ok := url.(*FileURL); ok {
// No need to download file URLs
return os.Open(fileUrl.Path)
return fileUrl.Path, nil
}

key := url.Key()
Expand All @@ -84,12 +93,14 @@ func (self *Context) Open(url URL) (*os.File, error) {

if self.files != nil {
if path, ok := self.files[key]; ok {
if file, err := os.Open(path); err == nil {
return file, nil
} else if os.IsNotExist(err) {
delete(self.files, key)
if ok, err := util.DoesFileExist(path); err == nil {
if ok {
return path, nil
} else {
delete(self.files, key)
}
} else {
return nil, err
return "", err
}
}
}
Expand All @@ -99,10 +110,11 @@ func (self *Context) Open(url URL) (*os.File, error) {
if self.files == nil {
self.files = make(map[string]string)
}
self.files[key] = file.Name()
return file, nil
path := file.Name()
self.files[key] = path
return path, nil
} else {
return nil, err
return "", err
}
}

Expand Down
Loading

0 comments on commit 185513f

Please sign in to comment.