-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathresource.go
More file actions
68 lines (59 loc) · 1.75 KB
/
resource.go
File metadata and controls
68 lines (59 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package url
import (
"context"
"encoding/json"
"github.com/viant/afs"
"github.com/viant/afs/file"
"github.com/viant/afs/url"
"github.com/viant/toolbox"
"gopkg.in/yaml.v3"
"strings"
)
//Resource represents a URL based resource, with enriched meta info
type Resource struct {
URL string `description:"resource URL or relative or absolute path" required:"true"` //URL of resource
Credentials string `description:"credentials file"` //name of credential file or credential key depending on implementation
CustomKey *AES256Key `description:" content encryption key"`
}
func (r *Resource) Init() (err error) {
r.URL = url.Normalize(r.URL, file.Scheme)
return err
}
//NewResource returns a new resource for provided URL, followed by optional credential, cache and cache expiryMs.
func NewResource(Params ...interface{}) *Resource {
if len(Params) == 0 {
return nil
}
var URL = toolbox.AsString(Params[0])
URL = url.Normalize(URL, file.Scheme)
var credential string
if len(Params) > 1 {
credential = toolbox.AsString(Params[1])
}
return &Resource{
URL: URL,
Credentials: credential,
}
}
//Decode decodes url's data into target, it support JSON and YAML exp.
func Decode(URL string, target interface{}) (err error) {
ctx := context.Background()
fs := afs.New()
data, err := fs.DownloadWithURL(ctx, URL)
if err != nil {
return err
}
aMap := map[string]interface{}{}
if strings.HasSuffix(URL, "yaml") {
aMap = map[string]interface{}{}
if err := yaml.Unmarshal(data, &aMap); err != nil {
return err
}
} else {
aMap = map[string]interface{}{}
if err := json.Unmarshal(data, &aMap); err != nil {
return err
}
}
return toolbox.DefaultConverter.AssignConverted(target, aMap)
}