forked from Permify/permify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecoder.go
More file actions
87 lines (75 loc) · 1.48 KB
/
Copy pathdecoder.go
File metadata and controls
87 lines (75 loc) · 1.48 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package validation
import (
"errors"
"io"
"net/http"
"net/url"
"os"
"path"
"gopkg.in/yaml.v3"
)
// Decoder - Decoder interface
type Decoder interface {
Decode(out interface{}) error
}
// NewDecoderFromURL - Creates new decoder
func NewDecoderFromURL(url *url.URL) (Decoder, error) {
switch url.Scheme {
case "file":
return NewFileDecoder(url.Path), nil
case "http", "https":
if url.Hostname() == "gist.github.com" {
url.Host = "gist.githubusercontent.com"
url.Path = path.Join(url.Path, "/raw")
}
return NewHTTPDecoder(url.String()), nil
case "":
return NewFileDecoder(url.Path), nil
default:
return nil, errors.New("unknown decoder type")
}
}
// FILE
type FileDecoder struct {
path string
}
func NewFileDecoder(path string) *FileDecoder {
return &FileDecoder{
path: path,
}
}
// Decode - Decode a file
func (d FileDecoder) Decode(out interface{}) (err error) {
file, err := os.Open(d.path)
if err != nil {
return err
}
data, err := io.ReadAll(file)
if err != nil {
return err
}
return yaml.Unmarshal(data, out)
}
// HTTP
type HTTPDecoder struct {
url string
}
// NewHTTPDecoder - Creates new HTTP decoder
func NewHTTPDecoder(url string) *HTTPDecoder {
return &HTTPDecoder{
url: url,
}
}
// Decode - decode HTTP
func (d HTTPDecoder) Decode(out interface{}) (err error) {
r, err := http.Get(d.url)
if err != nil {
return err
}
defer r.Body.Close()
data, err := io.ReadAll(r.Body)
if err != nil {
return err
}
return yaml.Unmarshal(data, out)
}