github.com/gogf/gf/v2@v2.7.4/encoding/gyaml/gyaml.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 // Package gyaml provides accessing and converting for YAML content. 8 package gyaml 9 10 import ( 11 "bytes" 12 "strings" 13 14 "gopkg.in/yaml.v3" 15 16 "github.com/gogf/gf/v2/errors/gerror" 17 "github.com/gogf/gf/v2/internal/json" 18 "github.com/gogf/gf/v2/util/gconv" 19 ) 20 21 // Encode encodes `value` to an YAML format content as bytes. 22 func Encode(value interface{}) (out []byte, err error) { 23 if out, err = yaml.Marshal(value); err != nil { 24 err = gerror.Wrap(err, `yaml.Marshal failed`) 25 } 26 return 27 } 28 29 // EncodeIndent encodes `value` to an YAML format content with indent as bytes. 30 func EncodeIndent(value interface{}, indent string) (out []byte, err error) { 31 out, err = Encode(value) 32 if err != nil { 33 return 34 } 35 if indent != "" { 36 var ( 37 buffer = bytes.NewBuffer(nil) 38 array = strings.Split(strings.TrimSpace(string(out)), "\n") 39 ) 40 for _, v := range array { 41 buffer.WriteString(indent) 42 buffer.WriteString(v) 43 buffer.WriteString("\n") 44 } 45 out = buffer.Bytes() 46 } 47 return 48 } 49 50 // Decode parses `content` into and returns as map. 51 func Decode(content []byte) (map[string]interface{}, error) { 52 var ( 53 result map[string]interface{} 54 err error 55 ) 56 if err = yaml.Unmarshal(content, &result); err != nil { 57 err = gerror.Wrap(err, `yaml.Unmarshal failed`) 58 return nil, err 59 } 60 return gconv.MapDeep(result), nil 61 } 62 63 // DecodeTo parses `content` into `result`. 64 func DecodeTo(value []byte, result interface{}) (err error) { 65 err = yaml.Unmarshal(value, result) 66 if err != nil { 67 err = gerror.Wrap(err, `yaml.Unmarshal failed`) 68 } 69 return 70 } 71 72 // ToJson converts `content` to JSON format content. 73 func ToJson(content []byte) (out []byte, err error) { 74 var ( 75 result interface{} 76 ) 77 if result, err = Decode(content); err != nil { 78 return nil, err 79 } else { 80 return json.Marshal(result) 81 } 82 }