Gin 中使用 go-ini 加载.ini 配置文件
Github 地址:https://github.com/go-ini/ini
官方文档:https://ini.unknwon.io/
package main
import (
"fmt"
"os"
"gopkg.in/ini.v1"
)
func main() {
config, err := ini.Load("./conf/app.ini")
if err != nil {
//失败
fmt.Printf("Fail to read file: %v", err)
os.Exit(1)
}
//获取ini里面的配置
fmt.Println("App Mode:", config.Section("").Key("app_name").String())
fmt.Println("App Mode:", config.Section("mysql").Key("password").String())
fmt.Println("App Mode:", config.Section("redis").Key("ip").String())
//给ini写入数据
config.Section("").Key("app_name").SetValue("成强")
config.Section("").Key("admin_path").SetValue("/admin")
config.SaveTo("./conf/app.ini")
实例:加载数据库配置
var DB *gorm.DB
var err error
func init() {
//读取.ini里面的数据库配置
config, err := ini.Load("./conf/app.ini")
if err != nil {
//失败
fmt.Printf("Fail to read file: %v", err)
os.Exit(1)
}
ip := config.Section("mysql").Key("ip").String()
port:= config.Section("mysql").Key("port").String()
user:= config.Section("mysql").Key("user").String()
password:= config.Section("mysql").Key("password").String()
database:= config.Section("mysql").Key("database").String()
fmt.Println("App Mode:", config.Section("mysql").Key("password").String())
fmt.Println("App Mode:", config.Section("redis").Key("ip").String())
//dsn := "gin:gin@tcp(111.229.91.20:3306)/gin?charset=utf8mb4&parseTime=True&loc=Local"
dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local",
user,
password,
ip,
port,
database)