Golang 配置文件相干操作
本文以读取数据库配置文件为例
1、JSON 文件
package main/* 解析 json 格局的配置文件文件内容如下:{ "type": "json", "postgres": { "host": "localhost", "port": 5432, "username": "postgres", "password": "postgres", "dbname": "bubble" }}*/import ( "encoding/json" "fmt" "io/ioutil" "os")// 定义第一级配置文件的构造体type Config struct { Type string Postgres DbConf // 数据类型为第二级配置文件的构造体名称}// 定义第二级配置文件的构造体 留神数据类型type DbConf struct { Host string `json:"host"` Port uint `json:"port"` Username string `json:"username"` Password string `json:"password"` DbName string `json:"dbname"`}// 定义配置文件构造体type JsonStruct struct {}// 创立配置文件的构造函数func NewJsonStruct() *JsonStruct { return &JsonStruct{}}// 加载配置文件func (jt *JsonStruct) Load(filename string, v interface{}) { // 读取配置文件 data, err := ioutil.ReadFile(filename) if err != nil { return } // 解析配置文件 err = json.Unmarshal(data, v) if err != nil { return }}func main() { JsonParse := NewJsonStruct() v := Config{} // 获取配置文件门路 osGwd, _ := os.Getwd() confPath := osGwd + "/conf_json.json" // 加载配置文件 JsonParse.Load(confPath, &v) fmt.Printf("配置文件的类型为 %s \n", v.Type) fmt.Printf("PG 数据库的配置为 %s \n", v.Postgres)}
2、YAML 文件(举荐)
package main/*解析 yaml 格局的配置文件文件内容如下:database: postgres: host: localhost port: 5432 username: postgres password: postgres dbname: bubble} */import ( "fmt" "gopkg.in/yaml.v2" "io/ioutil" "os")type YamlStruct struct {}func NewYamlStruct() *YamlStruct { return &YamlStruct{}}type YamlConfig struct { DataBase DataBase `yaml:"database"`}type DataBase struct { PgConf PgConf `yaml:"postgres"`}type PgConf struct { Host string `yaml:"host"` Port string `yaml:"port"` Username string `yaml:"username"` Password string `yaml:"password"` DbName string `yaml:"dbname"`}func (yam *YamlStruct) Load(filename string, v interface{}) { data, err := ioutil.ReadFile(filename) if err != nil { panic(err.Error()) } err = yaml.Unmarshal(data, v) if err != nil { panic(err.Error()) }}func main() { YamlStruct := NewYamlStruct() v := YamlConfig{} osGwd, _ := os.Getwd() confPath := osGwd + "/conf_yaml.yaml" YamlStruct.Load(confPath, &v) fmt.Printf("配置文件的数据为 %s \n", v.DataBase)}
3、INI 文件
package main/* 解析 ini 格局的配置文件文件内容如下:mode=debug[postgres]host=localhostport=5432username=postgrespassword=postgresdbname=bubble */import ( "fmt" "github.com/go-ini/ini" "os")//type Postgres struct {// Host string// Port uint// Username string// Password string// DbName string//}func main() { osGwd, _ := os.Getwd() confPath := osGwd + "/conf_ini.ini" config, err := ini.Load(confPath) if err != nil { panic(err.Error()) } // 能够间接读取配置,并设置默认值 mode := config.Section("").Key("mode").MustString("debug") fmt.Println(mode) postgres, err := config.GetSection("postgres") if err != nil { panic(err.Error()) } // 可通过 Key 去取值 fmt.Println(postgres.Key("host")) // localhost fmt.Println(postgres.Keys()) // [localhost 5432 postgres postgres bubble] fmt.Println(postgres.KeyStrings()) // [host port username password dbname]}