Golang 配置文件相关操作
Golang 配置文件相关操作
本文以读取数据库配置文件为例
1、JSON 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| package main
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 文件(推荐)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| package main
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 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| package main
import ( "fmt" "github.com/go-ini/ini" "os" )
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()) } fmt.Println(postgres.Key("host")) fmt.Println(postgres.Keys()) fmt.Println(postgres.KeyStrings()) }
|