From 97848bf3f97005a43bf53ae96617e3d38a15b8f7 Mon Sep 17 00:00:00 2001 From: Marin Ivanov Date: Sun, 14 Aug 2022 23:12:58 +0300 Subject: Add NewFsFromURL() --- fs.go | 27 ++++++++++++++++++++++++++- fs_test.go | 2 +- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/fs.go b/fs.go index c4d080b..9f5af23 100644 --- a/fs.go +++ b/fs.go @@ -3,6 +3,8 @@ package s3 import ( "context" "errors" + "fmt" + neturl "net/url" "os" "time" @@ -12,7 +14,8 @@ import ( ) var ( - ErrUnsupported = errors.New("unsupported operation") + ErrUnsupported = errors.New("unsupported operation") + ErrInvalidProtocol = errors.New("invalid protocol") ) type Fs struct { @@ -41,6 +44,28 @@ func NewFs(endpoint, bucket, accessKeyID, secretAccessKey string, useSSL bool) ( }, nil } +func NewFsFromURL(url string) (*Fs, error) { + r, err := neturl.ParseRequestURI(url) + if err != nil { + return nil, fmt.Errorf("failed to parse url: %w", err) + } + useSSL := false + switch r.Scheme { + case "http": + case "https": + useSSL = true + default: + return nil, ErrInvalidProtocol + + } + + endpoint := r.Host + bucket := r.Path[1:] + accessKeyId := r.User.Username() + secretAccessKey, _ := r.User.Password() + return NewFs(endpoint, bucket, accessKeyId, secretAccessKey, useSSL) +} + // The name of this FileSystem func (fs *Fs) Name() string { return "s3" diff --git a/fs_test.go b/fs_test.go index 5328a7a..f8b7db0 100644 --- a/fs_test.go +++ b/fs_test.go @@ -76,7 +76,7 @@ func TestFsStatNoExist(t *testing.T) { } func newTestFs() (*Fs, error) { - fs, err := NewFs("127.0.0.1:9000", "test-bucket", "testuser", "testsecret", false) + fs, err := NewFsFromURL("http://testuser:testsecret@127.0.0.1:9000/test-bucket") return fs, err } -- cgit v1.2.3