toml的简单说明与配置
https://github.com/bbangert/toml
toml简介
解析toml配置文件
server.toml
[Mongo]
connstr="localhost"
dbname="blogs"
usertab="users"
blogtab="blogs"
[servers]
ip = "localhost"
port = ":8086"
conf.go
解析代码与toml文件保持一致,数量也是
package config
import (
"errors"
"flag"
"fmt"
"github.com/BurntSushi/toml"
"os"
)
type Mongo struct {
Connstr string
DBName string
UserTab string
BlogTab string
}
type Server struct {
IP string
Port string
}
type Config struct {
//DB database `toml:"database"`
Mongo Mongo
Servers Server
}
var Conf *Config
func printHelp() {
fmt.Printf("%s -c config_file [-h] [-v]\n", os.Args[0])
}
func printVer() {
fmt.Printf("author :%s\n", "abc")
fmt.Printf("version:%s\n", "1.0.0")
fmt.Printf("time :%s\n", "2019-12")
}
func init() {
if getConfig() != nil {
os.Exit(-1)
}
fmt.Println(*Conf)
}
func getConfig() error {
configFile := flag.String("c", "", "config_file")
help := flag.Bool("h", false, "help")
ver := flag.Bool("v", false, "version")
flag.Parse()
if *help {
printHelp()
os.Exit(0)
}
if *ver {
printVer()
os.Exit(0)
}
if *configFile == "" {
printHelp()
return errors.New("no config file")
} else {
Conf = &Config{}
_, err := toml.DecodeFile(*configFile, Conf)
if err != nil {
fmt.Println("failed to decode config file", configFile, err)
return err
}
}
return nil
}
main.go添加
import _ "blog/config"
命令行 go build
$ ./blog -h
E:\code\go\blog\blog.exe -c config_file [-h] [-v]
$ ./blog -v
author :abc
version:1.0.0
time :2020-05-17 18:42:10.3490859 +0800 CST m=+0.025060301
admin@LAPTOP-F4QE2B2L MINGW64 /e/code/go/blog
$ ./blog -c etc/server.toml
{{localhost blogs users blogs} {localhost :8086}}
网友评论