一、下载依赖
go get -u gopkg.in/yaml.v2
二、创建yml
配置文件
# 相关配置
server:
# 端口
part: 8888
# banner 配置
banner:
# banner 文件的名字
name: banner.txt
# 是否加载
loading: true
# 数据库相关配置
data:
# 数据类型
data-type: mysql
# 数据库名称
database: test
# 链接
url: 'www.baidu.com'
# 用户名
username: long
# 密码
password: 123456
# 初始化SQL配置
init:
name: init.sql
status: true
# 测试数据SQL配置
test:
name: test.sql
status: false
三、创建结构体
type Config struct {
// 服务器相关配置
Server struct{
Part string `yml:"part"`
Banner struct{
Name string `yml:"name"`
Loading bool `yml:"loading"`
} `yml:"banner"`
} `yml:"server"`
// 数据库相关配置
Data struct{
DataType string `yml:"data-type"`
DataBase string `yml:"database"`
Url string `yml:"url"`
Username string `yml:"username"`
Password string `yml:"password"`
Init struct{
Name string `yml:"name"`
Status bool `yml:"status"`
} `yml:"init"`
Test struct{
Name string `yml:"name"`
Status bool `yml:"status"`
} `yml:"test"`
} `yml:"data"`
}
四、读取工具
func NewConfig() *Config {
return &Config{}
}
func (config *Config) ReadConfig() {
file, err := ioutil.ReadFile("config/config.yml")
if err != nil {
log.Fatalln("读取文件config.yml发生错误")
return
}
if yaml.Unmarshal(file, config) != nil {
log.Fatalln("解析文件config.yml发生错误")
return
}
fmt.Println(config)
}
五、使用
import (
"fmt"
"gin-web/config"
)
func init() {
config.NewConfig().ReadConfig()
}
func main() {
fmt.Println("Gin-Web,启动")
}
读取结果&{{8888 {banner.txt true}} { test www.baidu.com long 123456 {init.sql true} {test.sql false}}}