gyaml.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. // Package gyaml provides accessing and converting for YAML content.
  7. package gyaml
  8. import (
  9. "bytes"
  10. "strings"
  11. "gopkg.in/yaml.v3"
  12. "github.com/gogf/gf/v2/errors/gerror"
  13. "github.com/gogf/gf/v2/internal/json"
  14. "github.com/gogf/gf/v2/util/gconv"
  15. )
  16. // Encode encodes `value` to an YAML format content as bytes.
  17. func Encode(value interface{}) (out []byte, err error) {
  18. if out, err = yaml.Marshal(value); err != nil {
  19. err = gerror.Wrap(err, `yaml.Marshal failed`)
  20. }
  21. return
  22. }
  23. // EncodeIndent encodes `value` to an YAML format content with indent as bytes.
  24. func EncodeIndent(value interface{}, indent string) (out []byte, err error) {
  25. out, err = Encode(value)
  26. if err != nil {
  27. return
  28. }
  29. if indent != "" {
  30. var (
  31. buffer = bytes.NewBuffer(nil)
  32. array = strings.Split(strings.TrimSpace(string(out)), "\n")
  33. )
  34. for _, v := range array {
  35. buffer.WriteString(indent)
  36. buffer.WriteString(v)
  37. buffer.WriteString("\n")
  38. }
  39. out = buffer.Bytes()
  40. }
  41. return
  42. }
  43. // Decode parses `content` into and returns as map.
  44. func Decode(content []byte) (map[string]interface{}, error) {
  45. var (
  46. result map[string]interface{}
  47. err error
  48. )
  49. if err = yaml.Unmarshal(content, &result); err != nil {
  50. err = gerror.Wrap(err, `yaml.Unmarshal failed`)
  51. return nil, err
  52. }
  53. return gconv.MapDeep(result), nil
  54. }
  55. // DecodeTo parses `content` into `result`.
  56. func DecodeTo(value []byte, result interface{}) (err error) {
  57. err = yaml.Unmarshal(value, result)
  58. if err != nil {
  59. err = gerror.Wrap(err, `yaml.Unmarshal failed`)
  60. }
  61. return
  62. }
  63. // ToJson converts `content` to JSON format content.
  64. func ToJson(content []byte) (out []byte, err error) {
  65. var (
  66. result interface{}
  67. )
  68. if result, err = Decode(content); err != nil {
  69. return nil, err
  70. } else {
  71. return json.Marshal(result)
  72. }
  73. }