Skip to content

Commit

Permalink
add ini parse
Browse files Browse the repository at this point in the history
  • Loading branch information
memory125 committed Jan 24, 2022
1 parent db0d34c commit 8d29fe2
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
15 changes: 15 additions & 0 deletions configuration/inifile/conf/cfg.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
app_name = awesome web

# possible values: DEBUG, INFO, WARNING, ERROR, FATAL
log_level = DEBUG

[mysql]
ip = 127.0.0.1
port = 3306
user = dj
password = 123456
database = awesome

[redis]
ip = 127.0.0.1
port = 6381
20 changes: 20 additions & 0 deletions configuration/inifile/conf/inicfg.go
Original file line number Diff line number Diff line change
@@ -1 +1,21 @@
package conf

// MySQLConf ...
type MySQLConf struct {
IP string `ini:"ip"`
Port string `ini:"port"`
User string `ini:"user"`
Password string `ini:"password"`
Database string `ini:"database"`
}

// RedisConf ...
type RedisConf struct {
IP string `ini:"ip"`
Port string `ini:"port"`
}

type ProjectConf struct {
MySQLConf `ini:"mysql"`
RedisConf `ini:"redis"`
}
57 changes: 57 additions & 0 deletions configuration/inifile/main.go
Original file line number Diff line number Diff line change
@@ -1 +1,58 @@
package main

import (
"fmt"
"gopkg.in/ini.v1"
"log"
"wing.com/magic-golang/configuration/inifile/conf"
)

// ini文件解析示例
/*
ini解析库:
go get -u gopkg.in/ini.v1
*/

func main() {
cfg, err := ini.Load("./conf/cfg.ini")
if err != nil {
log.Fatal("Fail to read file: ", err)
}

fmt.Println("App Name:", cfg.Section("").Key("app_name").String())
fmt.Println("Log Level:", cfg.Section("").Key("log_level").String())

fmt.Println("MySQL IP:", cfg.Section("mysql").Key("ip").String())
mysqlPort, err := cfg.Section("mysql").Key("port").Int()
if err != nil {
log.Fatal(err)
}
fmt.Println("MySQL Port:", mysqlPort)
fmt.Println("MySQL User:", cfg.Section("mysql").Key("user").String())
fmt.Println("MySQL Password:", cfg.Section("mysql").Key("password").String())
fmt.Println("MySQL Database:", cfg.Section("mysql").Key("database").String())

fmt.Println("Redis IP:", cfg.Section("redis").Key("ip").String())
redisPort, err := cfg.Section("redis").Key("port").Int()
if err != nil {
log.Fatal(err)
}
fmt.Println("Redis Port:", redisPort)

var proCfg = new(conf.ProjectConf)
err = ini.MapTo(proCfg, "./conf/cfg.ini")
if err != nil {
fmt.Printf("load cfg.ini failed, error is %v.\n", err)
return
}
fmt.Println("=======MySQL==========")
fmt.Println("host: ", proCfg.MySQLConf.IP)
fmt.Println("port: ", proCfg.MySQLConf.Port)
fmt.Println("user: ", proCfg.MySQLConf.User)
fmt.Println("password: ", proCfg.MySQLConf.Password)
fmt.Println("database: ", proCfg.MySQLConf.Database)

fmt.Println("=======Redis==========")
fmt.Println("host: ", proCfg.RedisConf.IP)
fmt.Println("port: ", proCfg.RedisConf.Port)
}

0 comments on commit 8d29fe2

Please sign in to comment.