forked from guonaihong/gout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
yaml.go
51 lines (41 loc) · 897 Bytes
/
yaml.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
package encode
import (
"errors"
"io"
"github.com/xishengcai/gout/core"
"github.com/xishengcai/gout/encoder"
"gopkg.in/yaml.v2"
)
var ErrNotYAML = errors.New("Not yaml data")
// YAMLEncode yaml encoder structure
type YAMLEncode struct {
obj interface{}
}
// NewYAMLEncode create a new yaml encoder
func NewYAMLEncode(obj interface{}) encoder.Encoder {
if obj == nil {
return nil
}
return &YAMLEncode{obj: obj}
}
// Encode yaml encoder
func (y *YAMLEncode) Encode(w io.Writer) (err error) {
if v, ok := core.GetBytes(y.obj); ok {
if b := YAMLValid(v); !b {
return ErrNotYAML
}
_, err = w.Write(v)
return err
}
encode := yaml.NewEncoder(w)
return encode.Encode(y.obj)
}
// Name yaml Encoder name
func (y *YAMLEncode) Name() string {
return "yaml"
}
func YAMLValid(b []byte) bool {
var m map[string]interface{}
err := yaml.Unmarshal(b, &m)
return err == nil
}