读取配置文件到实体类中

91 阅读1分钟

文件目录结构 ├─.idea ├─config main.go

第一个方式,使用原生的yml类

1.创建接受yml文件实体类‘

` package config

type MysqlConfig struct {
Username string yaml:"username"
Password string yaml:"password"
}`

2.读取文件

package main

import (
"fmt"
"gopkg.in/yaml.v3"
config2 "gotest_test/config"
"io/ioutil"
"log"
)

func main() {
data, err := ioutil.ReadFile("config/config.yml")
if err == nil {
log.Println(err)
}
var config config2.MysqlConfig
if err := yaml.Unmarshal(data, &config); err != nil {
log.Println(err)
}
fmt.Println(config)
}

第二种方式:使用viper类

先获取依赖 go get github.com/spf13/viper

config类

type Config struct {
Host string mapstructure:"host"
Port int mapstructure:"port"
Username string mapstructure:"username"
Password string mapstructure:"password"
}

使用 // 设置 viper 的配置文件名和路径
viper.SetConfigName("config") // 文件名为 config.yaml
viper.AddConfigPath("config") // 在当前目录查找配置文件

// 读取配置文件
if err := viper.ReadInConfig(); err != nil {
panic(fmt.Errorf("读取配置文件出错: %s \n", err))
}

// 将配置文件的值映射到 Config 对象
var config config2.Config
if err := viper.Unmarshal(&config); err != nil {
panic(fmt.Errorf("映射配置文件出错: %s \n", err))
}

// 输出配置文件中的值
fmt.Printf("Host: %s\n", config.Host)
fmt.Printf("Port: %d\n", config.Port)
fmt.Printf("Username: %s\n", config.Username)
fmt.Printf("Password: %s\n", config.Password)