gyaml.go 931 B

123456789101112131415161718192021222324252627282930313233343536373839
  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. "github.com/gogf/gf/internal/json"
  10. "gopkg.in/yaml.v3"
  11. "github.com/gogf/gf/util/gconv"
  12. )
  13. func Encode(v interface{}) ([]byte, error) {
  14. return yaml.Marshal(v)
  15. }
  16. func Decode(v []byte) (interface{}, error) {
  17. var result map[string]interface{}
  18. if err := yaml.Unmarshal(v, &result); err != nil {
  19. return nil, err
  20. }
  21. return gconv.MapDeep(result), nil
  22. }
  23. func DecodeTo(v []byte, result interface{}) error {
  24. return yaml.Unmarshal(v, result)
  25. }
  26. func ToJson(v []byte) ([]byte, error) {
  27. if r, err := Decode(v); err != nil {
  28. return nil, err
  29. } else {
  30. return json.Marshal(r)
  31. }
  32. }