import ( "golang.org/x/tools/go/loader" "os" ) func LoadConfigFile(path string) (map[string]string, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() cfg := map[string]string{} err = loader.FromTOML(f, &cfg) if err != nil { return nil, err } return cfg, nil }
import ( "golang.org/x/tools/go/loader" "os" ) type AppConfig struct { Server struct { Port int `yaml:"port"` } `yaml:"server"` Database struct { Host string `yaml:"host"` Username string `yaml:"username"` Password string `yaml:"password"` } `yaml:"database"` } func LoadAppConfigFile(path string) (*AppConfig, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() cfg := &AppConfig{} err = loader.FromYAML(f, cfg) if err != nil { return nil, err } return cfg, nil }In this example, we use the FromYAML function provided by Config Import to parse a YAML formatted configuration file, and store the parsed values in a struct named AppConfig. This struct contains nested structs corresponding to different sections of the configuration file, and uses YAML tags to map YAML keys to struct fields. This function will return an error if the file cannot be opened or if the file contents cannot be parsed as YAML. Overall, the go golang.org.x.tools.go.loader Config Import package provides a flexible and easy-to-use way to load and parse configuration files in Go applications, making it simpler to manage application settings and configurations.