-
Notifications
You must be signed in to change notification settings - Fork 186
/
encoding.go
57 lines (44 loc) · 850 Bytes
/
encoding.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
package ext
import (
"encoding/json"
"io"
"gopkg.in/yaml.v2"
)
type Encoding string
const (
EncodingYML Encoding = "yml"
EncodingYAML Encoding = "yaml"
EncodingJSON Encoding = "json"
)
func (e Encoding) NewEncoder(w io.Writer) EncodeCloser {
switch e {
case EncodingYML, EncodingYAML:
return yaml.NewEncoder(w)
case EncodingJSON:
return NopCloseEncoder{json.NewEncoder(w)}
}
return nil
}
type Encoder interface {
Encode(any) error
}
type EncodeCloser interface {
Encoder
Close() error
}
type NopCloseEncoder struct {
Encoder
}
func (n NopCloseEncoder) Close() error { return nil }
func (e Encoding) NewDecoder(r io.Reader) Decoder {
switch e {
case EncodingYML, EncodingYAML:
return yaml.NewDecoder(r)
case EncodingJSON:
return json.NewDecoder(r)
}
return nil
}
type Decoder interface {
Decode(any) error
}