[TOC]
0x00 前言简述 描述: 作为开发者相信对应用程序的配置文件并不陌生吧,例如 Java Spring Boot 里的 class 目录中程序配置,当然go语言相关项目也是可以根据配置文件的格式内容进行读取的,常规的配置文件格式有 json、ini、yaml (个人推荐)、properties 等,我们可以使用其为程序配置一些初始化的可变参数,例如 数据库字符串链接以及认证密码等等。
好,下面作者将依次从json、ini、以及yaml 等顺序进行讲解。
0x01 常用模块 encoding/json 模块 - json 配置文件解析 config.json 配置文件示例
[TOC]
0x00 前言简述 描述: 作为开发者相信对应用程序的配置文件并不陌生吧,例如 Java Spring Boot 里的 class 目录中程序配置,当然go语言相关项目也是可以根据配置文件的格式内容进行读取的,常规的配置文件格式有 json、ini、yaml (个人推荐)、properties 等,我们可以使用其为程序配置一些初始化的可变参数,例如 数据库字符串链接以及认证密码等等。
好,下面作者将依次从json、ini、以及yaml 等顺序进行讲解。
0x01 常用模块 encoding/json 模块 - json 配置文件解析 config.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 { "app" : { "app_name" : "hello-gin" , "app_mode" : "dev" , "app_host" : "localhost" , "app_port" : "8080" , "app_secret" : "weiyigeek.top" }, "log" :{ "log_name" : "app" , "log_path" : "/logs" , "log_age" : "180" , "log_rotation_time" : "24" }, "db" : { "mysql" : { "mysql_user" : "root" , "mysql_pass" : "123456" , "mysql_addr" : "localhost" , "mysql_port" : "3306" , "mysql_database" : "test" }, "redis" : { "redis_addr" : "localhost" , "redis_port" : "6379" , "redis_database" : "9" , "redis_pass" : "123456" } } }
LoadJSONConfig函数进行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 package configimport ( "encoding/json" "log" "os" ) type AppJSONConfig struct { AppName string `json:"app_name"` AppMode string `json:"app_mode"` AppHost string `json:"app_host"` AppPort string `json:"app_port"` AppSecret string `json:"app_secret"` } type LogJSONConfig struct { LogPath string `json:"log_path"` LogName string `json:"log_name"` LogAge string `json:"log_age"` LogRotationTime string `json:"log_rotation_time"` } type DbMySQLJSONConfig struct { User string `json:"mysql_user"` Pass string `json:"mysql_pass"` Addr string `json:"mysql_addr"` Port string `json:"mysql_port"` Database string `json:"mysql_database"` } type DbRedisJSONConfig struct { Addr string `json:"redis_addr"` Port string `json:"redis_port"` Pass string `json:"redis_pass"` Database string `json:"redis_database"` } type DbJSONConfig struct { Mysql DbMySQLJSONConfig `json:"mysql"` Redis DbRedisJSONConfig `json:"redis"` } type JSONConfig struct { App AppJSONConfig `json:"app"` Log LogJSONConfig `json:"log"` Db DbJSONConfig `json:"db"` } func LoadJSONConfig (path string ) *JSONConfig { var Config JSONConfig f, err := os.Open(path) if err != nil { log.Printf("Open config file failed!" ) panic (err) } defer f.Close() decoder := json.NewDecoder(f) decode_err := decoder.Decode(&Config) if err != nil { panic (decode_err) } return &Config }
函数执行入口: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 package mainimport ( "fmt" "hello-gin/util/config" ) func main () { conf := config.LoadJSONConfig() fmt.Print(conf, "\n" ) fmt.Println("----------------------------------" ) fmt.Println("应用名称" , conf.App.AppName) fmt.Println("应用密钥" , conf.App.AppSecret) }
执行结果:1 2 3 4 5 > go run .\main.go &{{hello-gin dev localhost 8080 weiyigeek.top} {/logs app debug} {{root 123456 localhost 3306 test} {localhost 6379 123456 9 }}} ---------------------------------- 应用名称 hello-gin 应用密钥 weiyigeek.top
gopkg.in/ini.v1 模块 - ini 配置文件解析 在Go中读取INI文件,我们可以使用名为go-ini的第三方库(a third-party library),它是一个非常方便、高效的go配置文件操作库。
模块下载: go get -v -u gopkg.in/ini.v1
config.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 [app] name ="hellogin" mode ="dev" host ="localhost" port =8080 secret ="weiyigeek" [log] name ="ginDemo" path ="D:/Study/Project/Go/hello-gin/logs" maxage =180 rotation_time =24 rotation_size =100 [mysql] host =192.168 .2.2 port =3306 user =weiyigeekpass =123456 database =weiyigeek[redis] host =192.168 .2.6 port =6379 pass =weiyigeek.topdatabase =10
LoadINIConfig 读取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 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 75 76 77 78 79 80 81 82 package configimport ( "fmt" "gopkg.in/ini.v1" ) type AppINIConfig struct { AppName string `ini:"name"` AppMode string `ini:"mode"` AppHost string `ini:"host"` AppPort int `ini:"port"` AppSecret string `ini:"secret"` } type LogINIConfig struct { LogPath string `ini:"path"` LogName string `ini:"name"` LogAge int `ini:"age"` LogRotationTime int `ini:"rotation_time"` LogRotationSize int `ini:"rotation_size"` } type DbMysqlINIConfig struct { User string `ini:"user"` Pass string `ini:"pass"` Host string `ini:"addr"` Port int `ini:"port"` Database string `ini:"database"` } type DbRedisINIConfig struct { Host string `ini:"addr"` Port int `ini:"port"` Pass string `ini:"pass"` Database string `ini:"database"` } type INIConfig struct { App AppINIConfig `ini:"app"` Log LogINIConfig `ini:"log"` DbMysql DbMysqlINIConfig `ini:"mysql"` DbRedis DbMysqlINIConfig `ini:"redis"` } func LoadINIConfig (path string ) *INIConfig { config := &INIConfig{} cfg, err := ini.Load(path) if err != nil { fmt.Println("配置文件读取错误,请检查文件路径:" , err) panic (err) } config.App.AppName = cfg.Section("app" ).Key("name" ).String() config.App.AppMode = cfg.Section("app" ).Key("mode" ).MustString("dev" ) config.App.AppHost = cfg.Section("app" ).Key("host" ).MustString("localhost" ) config.App.AppPort = cfg.Section("app" ).Key("port" ).MustInt(8080 ) config.App.AppSecret = cfg.Section("app" ).Key("secret" ).String() config.Log.LogName = cfg.Section("log" ).Key("name" ).String() config.Log.LogPath = cfg.Section("log" ).Key("path" ).String() config.Log.LogAge = cfg.Section("log" ).Key("maxage" ).MustInt(180 ) config.Log.LogRotationSize = cfg.Section("log" ).Key("rotation_time" ).MustInt(24 ) config.Log.LogRotationTime = cfg.Section("log" ).Key("rotation_size" ).MustInt(100 ) config.DbMysql.Host = cfg.Section("mysql" ).Key("host" ).String() config.DbMysql.Port = cfg.Section("mysql" ).Key("port" ).MustInt(3306 ) config.DbMysql.User = cfg.Section("mysql" ).Key("user" ).String() config.DbMysql.Pass = cfg.Section("mysql" ).Key("pass" ).String() config.DbMysql.Database = cfg.Section("mysql" ).Key("database" ).String() config.DbRedis.Host = cfg.Section("redis" ).Key("host" ).String() config.DbRedis.Port = cfg.Section("redis" ).Key("port" ).MustInt(6379 ) config.DbRedis.Pass = cfg.Section("redis" ).Key("pass" ).String() config.DbRedis.Database = cfg.Section("redis" ).Key("database" ).String() return config }
main 函数入口调用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 package mainimport ( "fmt" "hello-gin/util/config" ) func main () { confINI := config.LoadINIConfig("configs/config.ini" ) fmt.Println(confINI) fmt.Println("App : " , confINI.App) fmt.Println("Log : " , confINI.Log) fmt.Println("Database :" , confINI.DbRedis.Database) }
执行结果:1 2 3 4 5 go run .\main.go &{{hellogin dev localhost 8080 weiyigeek} {D:/Study/Project/Go/hello-gin/logs ginDemo 180 100 24} {weiyigeek 123456 192.168.2.2 3306 weiyigeek} { weiyigeek.top 192.168.2.6 6379 10}} App : {hellogin dev localhost 8080 weiyigeek} Log : {D:/Study/Project/Go/hello-gin/logs ginDemo 180 100 24} Database : 10
gopkg.in/yaml.v3 模块 - yaml 配置文件解析 描述: gopkg.in/yaml.v3 包使Go程序能够轻松地对yaml值进行编码和解码, 它是作为juju项目的一部分在Canonical中开发的,基于著名的libyaml C库的纯Go端口,可以快速可靠地解析和生成YAML数据。
项目地址: https://github.com/go-yaml/yaml
模块包下载: go get -v -u gopkg.in/yaml.v3
config.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 app: name: "hellogin" mode: "dev" host: "localhost" port: "8080" secret: "weiyigeek" log: name: "ginDemo" path: "D:/Study/Project/Go/hello-gin/logs" maxage: 180 rotation_time: 24 rotation_size: 100 db: mysql: host: 192.168 .2 .2 port: 3306 user: weiyigeek pass: 123456 database: weiyigeek redis: host: 192.168 .2 .6 port: 3306 pass: weiyigeek.top database: 10 user: user: - weiyigeek - geeker mqtt: host: 192.168 .2 .7 :1883 username: weiyigeek password: weiyigeek.top
LoadYAMLConfig 函数读取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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 package configimport ( "fmt" "io/ioutil" "log" "gopkg.in/yaml.v3" ) type AppYAMLConfig struct { AppName string `yaml:"name"` AppMode string `yaml:"mode"` AppHost string `yaml:"host"` AppPort string `yaml:"port"` AppSecret string `yaml:"secret"` } type LogYAMLConfig struct { LogPath string `yaml:"path"` LogName string `yaml:"name"` LogAge string `yaml:"age"` LogRotationTime string `yaml:"rotation_time"` LogRotationSize string `yaml:"rotation_size"` } type DbMySQLYAMLConfig struct { User string `yaml:"user"` Pass string `yaml:"pass"` Addr string `yaml:"addr"` Port string `yaml:"port"` Database string `yaml:"database"` } type DbRedisYAMLConfig struct { Addr string `yaml:"addr"` Port string `yaml:"port"` Pass string `yaml:"pass"` Database string `yaml:"database"` } type DbYAMLConfig struct { Mysql DbMySQLYAMLConfig `yaml:"mysql"` Redis DbRedisYAMLConfig `yaml:"redis"` } type MqttYAMLconfig struct { Host string `yaml:"host"` Username string `yaml:"username"` Password string `yaml:"password"` } type UserYAMLconfig struct { User []string `yaml:"user"` Mqtt MqttYAMLconfig `yaml:"mqtt"` } type YAMLConfig struct { App AppYAMLConfig `yaml:"app"` Log LogYAMLConfig `yaml:"log"` Db DbYAMLConfig `yaml:"db"` User UserYAMLconfig `yaml:"user"` } func LoadYAMLConfig (path string ) *YAMLConfig { config := &YAMLConfig{} yamlFile, err := ioutil.ReadFile(path) if err != nil { log.Printf("Open config.yaml failed!" ) panic (err) } err = yaml.Unmarshal(yamlFile, config) if err != nil { log.Printf("yaml config file Unmarsha failed!" ) panic (err) } return config }
入口函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 package mainimport ( "fmt" "hello-gin/util/config" ) func main () { confYAML := config.LoadYAMLConfig("configs/config.yaml" ) fmt.Print(confYAML, "\n" ) fmt.Println("--------------------------------------------------------------" ) fmt.Println("应用用户" , confYAML.User.User) fmt.Println("应用名称" , confYAML.App.AppName) fmt.Println("应用密钥" , confYAML.App.AppSecret) fmt.Println("MySQL账号密码:" , confYAML.Db.Mysql.User, confYAML.Db.Mysql.Pass) }
执行结果:1 2 3 4 5 &{{hellogin dev localhost 8080 weiyigeek} {D:/Study/Project/Go/hello-gin/logs ginDemo 24 100} {{weiyigeek 123456 3306 weiyigeek} { 3306 weiyigeek.top 10}} {[weiyigeek geeker] {192.168.2.7:1883 weiyigeek weiyigeek.top}}} -------------------------------------------------------------- 应用用户 [weiyigeek geeker] 应用名称 hellogin 应用密钥 weiyigeek
spf13/viper 模块 - 配置文件解析终结者 描述: 在前面实践中作者分别用了三种模块包以原生包针对四种不同配置的文件,那到底有没有引入一个包就可以全部解析的呢? 既然这么问,那答案显然是可以的, 那就是今天的主人公 viper 项目地址: github.com/spf13/viper
viper 适用于Go应用程序(包括[Twelve-Factor App)的完整配置解决方案,它被设计用于在应用程序中工作,并且可以处理所有类型的配置需求和格式,它支持以下特性:
设置默认值以及显式配置值
从JSON、TOML、YAML、HCL、envfile和Java properties格式的配置文件读取配置信息
var SupportedExts = []string{“json”, “toml”, “yaml”, “yml”, “properties”, “props”, “prop”, “hcl”, “tfvars”, “dotenv”, “env”, “ini”}
实时监控和重新读取配置文件(可选)
从环境变量中读取
从远程配置系统(etcd或Consul)读取并监控配置变化
var SupportedRemoteProviders = []string{“etcd”, “etcd3”, “consul”, “firestore”}
从命令行参数读取配置
从buffer读取配置
Viper 优先级
显示调用Set设置值
命令行参数(flag)
环境变量
配置文件
key/value存储
默认值
PS: 目前Viper配置的键(Key)是大小写不敏感的。
模块下载安装: go get github.com/spf13/viper
常用函数
温馨提示: 每一个Get方法在找不到值的时候都会返回零值, 为了检查给定的键是否存在,提供了IsSet()方法.
参考地址: https://github.com/spf13/viper/blob/master/README.md
常规使用 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 75 76 77 78 79 80 81 82 83 84 viper.SetDefault("ContentDir" , "content" ) viper.SetDefault("LayoutDir" , "layouts" ) viper.SetDefault("Taxonomies" , map [string ]string {"tag" : "tags" , "category" : "categories" }) viper.SetConfigFile("config.yaml" ) viper.AddConfigPath("/etc/appname/" ) viper.SetConfigName("config" ) viper.SetConfigType("yaml" ) viper.AddConfigPath("/etc/appname/" ) viper.AddConfigPath("$HOME/.appname" ) viper.AddConfigPath("." ) if err := viper.ReadInConfig(); err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); ok { } else { } } else { } viper.Set("Verbose" , true ) viper.Set("LogFile" , LogFile) fmt.Println(viper.Get("mysql" )) fmt.Println(viper.Get("mysql.url" )) { "host" : { "address" : "localhost" , "port" : 5799 }, "datastore" : { "mysql" : { "host" : "127.0.0.1" , "port" : 3306 } } } viper.GetString("datastore.mysql.host" ) app: cache1: max-items: 100 item-size: 64 cache2: max-items: 200 item-size: 80 subv := viper.Sub("app.cache1" ) type Config struct { Port int `mapstructure:"port"` Version string `mapstructure:"version"` } var Conf = new (Config)if err := viper.Unmarshal(Conf); err != nil { panic (fmt.Errorf("unmarshal conf failed, err:%s \n" , err)) } viper.WatchConfig() viper.OnConfigChange(func (in fsnotify.Event) { fmt.Println("配置文件被修改了" ) if err := viper.Unmarshal(Conf); err != nil { panic (fmt.Errorf("unmarshal conf failed, err:%s \n" , err)) } })
示例1.Viper支持Cobra库中使用的Pflag绑定并输出
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 package mainimport ( "flag" "fmt" "github.com/spf13/pflag" "github.com/spf13/viper" ) func main () { flag.Int("flagname" , 1234 , "help message for flagname" ) pflag.CommandLine.AddGoFlagSet(flag.CommandLine) pflag.Parse() viper.BindPFlags(pflag.CommandLine) i := viper.GetInt("flagname" ) fmt.Println(i) }
示例2.使用viper读取yaml并存放在结构体中 configs\prod.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 app: name: "hellogin" mode: "dev" host: "localhost" port: "8080" secret: "weiyigeek" version: "v1.2.0" log: name: "ginDemo" path: "D:/Study/Project/Go/hello-gin/logs" maxage: 180 rotation_time: 24 rotation_size: 100 db: mysql: host: 192.168 .2 .2 port: 3306 user: weiyigeek pass: 123456 database: weiyigeek redis: host: 192.168 .2 .6 port: 3306 pass: weiyigeek.top database: 10
代码示例: 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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 package mainimport ( "fmt" "github.com/fsnotify/fsnotify" "github.com/spf13/viper" ) type AppYAMLConfig struct { AppName string `mapstructure:"name"` AppMode string `mapstructure:"mode"` AppHost string `mapstructure:"host"` AppPort string `mapstructure:"port"` AppSecret string `mapstructure:"secret"` AppVersion string `mapstructure:"version"` } type LogYAMLConfig struct { LogPath string `mapstructure:"path"` LogName string `mapstructure:"name"` LogAge string `mapstructure:"age"` LogRotationTime string `mapstructure:"rotation_time"` LogRotationSize string `mapstructure:"rotation_size"` } type DbMySQLYAMLConfig struct { User string `mapstructure:"user"` Pass string `mapstructure:"pass"` Addr string `mapstructure:"addr"` Port string `mapstructure:"port"` Database string `mapstructure:"database"` } type DbRedisYAMLConfig struct { Addr string `mapstructure:"addr"` Port string `mapstructure:"port"` Pass string `mapstructure:"pass"` Database string `mapstructure:"database"` } type DbYAMLConfig struct { Mysql DbMySQLYAMLConfig `mapstructure:"mysql"` Redis DbRedisYAMLConfig `mapstructure:"redis"` } type MqttYAMLconfig struct { Host string `mapstructure:"host"` Username string `mapstructure:"username"` Password string `mapstructure:"password"` } type YAMLConfig struct { App AppYAMLConfig `mapstructure:"app"` Log LogYAMLConfig `mapstructure:"log"` Db DbYAMLConfig `mapstructure:"db"` } func NewConfig (name string ) *viper .Viper { vp := viper.New() vp.SetConfigName(name) vp.SetConfigType("yaml" ) vp.AddConfigPath("./configs/" ) if err := vp.ReadInConfig(); err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); ok { fmt.Printf("配置文件未找到!%v\n" , err) return nil } else { fmt.Printf("找到配置文件,但是解析错误,%v\n" , err) return nil } } return vp } func main () { vp := NewConfig("prod" ) fmt.Println("Version : " , vp.Get("app.version" )) fmt.Println(vp.GetStringMap("app" )) v := vp.GetStringMap("app" ) fmt.Println("version : " , v["version" ], "\n" ) conf := new (YAMLConfig) if err := vp.Unmarshal(conf); err != nil { fmt.Printf("解析错误: %v\n" , err) panic (err) } fmt.Println(conf, "\n" ) vp.WatchConfig() vp.OnConfigChange(func (in fsnotify.Event) { fmt.Println("配置文件被修改了" ) if err := vp.Unmarshal(conf); err != nil { panic (fmt.Errorf("unmarshal conf failed, err:%s \n" , err)) } }) fmt.Println(vp) }
执行结果: 1 2 3 4 5 6 7 8 9 go run .\main.go Version : v1.2.0 map[host:localhost mode:dev name:hellogin port:8080 secret:weiyigeek version:v1.2.0] version : v1.2.0 &{{hellogin dev localhost 8080 weiyigeek v1.2.0} {D:/Study/Project/Go/hello-gin/logs ginDemo 24 100} {{weiyigeek 123456 3306 weiyigeek} { 3306 weiyigeek.top 10}}} &{. [D:\Study\Project\Go\hello-gin\configs] 0x1235c48 [] prod D:\Study\Project\Go\hello-gin\configs\prod.yaml yaml 420 {false false false false false false false false false false false false false false false [] false <nil> 0 false false } false <nil> false map[app:map[host:localhost mode:dev name:hellogin port:8080 secret:weiyigeek version:v1.2.0] db:map[mysql:map[database:weiyigeek host:192.168.2.2 pass:123456 port:3306 user:weiyigeek] redis:map[database:10 host:192.168.2.6 pass:weiyigeek.top port:3306]] log :map[maxage:180 name:ginDemo path:D:/Study/Project/Go/hello-gin/logs rotation_size:100 rotation_time:24]] map[] map[] map[] map[] map[] map[] false 0xfa25a0 {} 0xc000066860 0xc000066880}
原生map结构 - properties 配置文件解析 properties 配置文件 1 2 3 4 5 6 7 8 9 10 11 appName =hellogin appMode =dev appHost =localhost appPort =8080 appSecret ="WeiyiGeek" logName ="ginDemo" logPath ="D:/Study/Project/Go/hello-gin/logs" logMaxage =180 logRotationTime =24 logRotationSize =100
LoadPropConfig 函数读取properties配置文件 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 package configimport ( "bufio" "fmt" "io" "os" "strings" ) var properties = make (map [string ]string )func LoadPropConfig (path string ) map [string ]string { propFile, err := os.OpenFile(path, os.O_RDONLY, 0666 ) if err != nil { fmt.Println("打开 config.properties 配置文件失败!" ) panic (err) } propReader := bufio.NewReader(propFile) for { prop, err := propReader.ReadString('\n' ) if err != nil { if err == io.EOF { break } } if (len (prop) == 0 ) || (prop == "\n" ) { continue } properties[strings.Replace(strings.Split(prop, "=" )[0 ], " " , "" , -1 )] = strings.Replace(strings.Split(prop, "=" )[1 ], " " , "" , -1 ) } return properties }
函数调用主入口 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 package mainimport ( "fmt" "hello-gin/util/config" ) func main () { properties := config.LoadPropConfig("configs/config.properties" ) fmt.Println(properties) fmt.Print("AppName : " , properties["appName" ]) fmt.Println("LogPath : " , properties["logPath" ]) }
执行结果:1 2 3 4 5 6 7 8 9 10 11 12 13 $ go run .\main.go map[appHost:localhost appMode:dev appName:hellogin appPort:8080 appSecret:"WeiyiGeek" logMaxage:180 logName:"ginDemo" logPath:"D:/Study/Project/Go/hello-gin/logs" logRotationTime:24 ] AppName : hellogin LogPath : "D:/Study/Project/Go/hello-gin/logs"