-
Notifications
You must be signed in to change notification settings - Fork 0
/
path_or_payload.go
84 lines (65 loc) · 1.25 KB
/
path_or_payload.go
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
package cli
import (
"bufio"
"encoding/json"
"fmt"
"io"
"io/fs"
"strings"
sfs "git.sr.ht/~istvan_bozso/shutil/fs"
)
type Decoder interface {
Decode(io.Reader, interface{}) error
}
type PathOrPayload struct {
data string
}
func (p *PathOrPayload) Set(s string) (err error) {
p.data = s
return nil
}
type ParseConfig struct {
fsys fs.FS
decoder Decoder
}
func (p ParseConfig) ParseStringPayload(s string, v interface{}) (err error) {
var r io.Reader
isFile, err := IsFile(p.fsys, s)
if err != nil {
return
}
if isFile {
file, err := p.fsys.Open(s)
if err != nil {
return err
}
defer file.Close()
r = file
} else {
r = strings.NewReader(s)
}
return p.decoder.Decode(bufio.NewReader(r), v)
}
func (p ParseConfig) Parse(pp PathOrPayload, v interface{}) (err error) {
return p.ParseStringPayload(pp.data, v)
}
type JSONCoder struct{}
func (JSONCoder) Decode(r io.Reader, v interface{}) (err error) {
return json.NewDecoder(r).Decode(v)
}
type Coder int
const (
CoderJSON Coder = iota
)
func (c Coder) GetDecoder() (d Decoder) {
switch c {
case CoderJSON:
return JSONCoder{}
default:
panic("unrecognized coder variant")
}
}
var DefaultParser = ParseConfig{
decoder: CoderJSON.GetDecoder(),
fsys: sfs.OS(),
}