123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- package yaml_loader
- import (
- "bytes"
- "fmt"
- "github.com/pkg/errors"
- "gopkg.in/yaml.v3"
- "io"
- "os"
- "reflect"
- )
- type LoadMapCallback func(objectMap map[string]any) error
- func LoadYamlFile(yamlFilePath string, retObjects *[]any) error {
- yamlFile, err := os.Open(yamlFilePath)
- if err != nil {
- return err
- }
- defer func(yamlFile *os.File) {
- err := yamlFile.Close()
- if err != nil {
- fmt.Println(err)
- }
- }(yamlFile)
- return loadYaml(yamlFile, retObjects)
- }
- func LoadYamlBytes(yamlBytes []byte, retObjects *[]any) error {
- return loadYaml(bytes.NewReader(yamlBytes), retObjects)
- }
- func LoadYamlMapFile(yamlFilePath string, callback LoadMapCallback) error {
- yamlFile, err := os.Open(yamlFilePath)
- if err != nil {
- return err
- }
- defer func(yamlFile *os.File) {
- err := yamlFile.Close()
- if err != nil {
- fmt.Println(err)
- }
- }(yamlFile)
- return loadYamlMap(yamlFile, callback)
- }
- func LoadYamlMapBytes(yamlBytes []byte, callback LoadMapCallback) error {
- return loadYamlMap(bytes.NewReader(yamlBytes), callback)
- }
- func loadYaml(r io.Reader, retObjects *[]any) error {
- decoder := yaml.NewDecoder(r)
- for i := 0; i < len(*retObjects); i++ {
- retObject := (*retObjects)[i]
- retObjectType := reflect.TypeOf(retObject)
- if retObjectType.Kind() != reflect.Ptr && retObjectType.Kind() != reflect.Map {
- return errors.New("返回对象slice需要指针或者map")
- }
- err := decoder.Decode(retObject)
- if err != nil {
- if err == io.EOF {
- break
- }
- return err
- }
- }
- return nil
- }
- func loadYamlMap(r io.Reader, callback LoadMapCallback) error {
- decoder := yaml.NewDecoder(r)
- for {
- object := make(map[string]any)
- err := decoder.Decode(object)
- if err != nil {
- if err == io.EOF {
- break
- }
- return err
- }
- err = callback(object)
- if err != nil {
- return err
- }
- }
- return nil
- }
|