gyaml.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. func Encode(value interface{}) (out []byte, err error) {
  17. if out, err = yaml.Marshal(value); err != nil {
  18. err = gerror.Wrap(err, `yaml.Marshal failed`)
  19. }
  20. return
  21. }
  22. func EncodeIndent(value interface{}, indent string) (out []byte, err error) {
  23. out, err = Encode(value)
  24. if err != nil {
  25. return
  26. }
  27. if indent != "" {
  28. var (
  29. buffer = bytes.NewBuffer(nil)
  30. array = strings.Split(strings.TrimSpace(string(out)), "\n")
  31. )
  32. for _, v := range array {
  33. buffer.WriteString(indent)
  34. buffer.WriteString(v)
  35. buffer.WriteString("\n")
  36. }
  37. out = buffer.Bytes()
  38. }
  39. return
  40. }
  41. func Decode(value []byte) (interface{}, error) {
  42. var (
  43. result map[string]interface{}
  44. err error
  45. )
  46. if err = yaml.Unmarshal(value, &result); err != nil {
  47. err = gerror.Wrap(err, `yaml.Unmarshal failed`)
  48. return nil, err
  49. }
  50. return gconv.MapDeep(result), nil
  51. }
  52. func DecodeTo(value []byte, result interface{}) (err error) {
  53. err = yaml.Unmarshal(value, result)
  54. if err != nil {
  55. err = gerror.Wrap(err, `yaml.Unmarshal failed`)
  56. }
  57. return
  58. }
  59. func ToJson(value []byte) (out []byte, err error) {
  60. var (
  61. result interface{}
  62. )
  63. if result, err = Decode(value); err != nil {
  64. return nil, err
  65. } else {
  66. return json.Marshal(result)
  67. }
  68. }