Home > Software engineering >  How to create a reusable code in Golang to read different yamls and put them into different structs
How to create a reusable code in Golang to read different yamls and put them into different structs

Time:12-15

I have to read let say 2 or 3 or more yamls that are different in structure and have a struct for each of those structures where I want to store them. So far I am creating separate functions for each and it works, but does not look very elegant... I think.

Here are the functions today:

// read the Yaml into struct(s)
type Config struct {...}
type ExecuteQueries struct {...}
func parseYamlConfig(pathYaml string) Config {
    myConfig := Config{}
    var err error
    var yamlFile []byte
    if pathYaml == "" {
        yamlFile, err = ioutil.ReadFile("./conf/conf.yaml")
    } else {
        yamlFile, err = ioutil.ReadFile(pathYaml)
    }
    if err != nil {
        log.Fatalf("error: %v", err)
    }
    err = yaml.Unmarshal([]byte(yamlFile), &myConfig)
    if err != nil {
        log.Fatalf("error: %v", err)
    }
    return myConfig
}
func parseYamlConfig2(pathYaml string) ExecuteQueries {
    myConfig := ExecuteQueries{}
    var err error
    var yamlFile []byte
    if pathYaml == "" {
        yamlFile, err = ioutil.ReadFile("./conf/conf.yaml")
    } else {
        yamlFile, err = ioutil.ReadFile(pathYaml)
    }
    if err != nil {
        log.Fatalf("error: %v", err)
    }
    err = yaml.Unmarshal([]byte(yamlFile), &myConfig)
    if err != nil {
        log.Fatalf("error: %v", err)
    }
    return myConfig
}

Notice that they are actually different in what they return and what they receive, but the processing of data is very similar. How should this be expressed in a more elegant way?

CodePudding user response:

func unmarshalYAMLFile(path string, v interface{}) error {
    if path == "" {
        path = "./conf/conf.yaml"
    }

    f, err := os.Open(path)
    if err != nil {
        return err
    }
    defer f.Close()
    
    return yaml.NewDecoder(f).Decode(v)
}
conf1 := Config{}
if err := unmarshalYAMLFile("/path/to/conf.yaml", &conf1); err != nil {
    panic(err)
}

conf2 := ExecuteQueries{}
if err := unmarshalYAMLFile("/path/to/conf_2.yaml", &conf2); err != nil {
    panic(err)
}
  • Related