标签 ini 下的文章

使用section.key的形式读取ini配置项

本文永久链接 – https://tonybai.com/2021/07/10/read-ini-config-item-by-passing-section-key

配置文件读取是很多Go项目必备的功能,这方面社区提供的方案也相对成熟稳定。但之前写这部分代码时除了使用了针对不同配置文件格式(比如:ini、toml等)的驱动包之外,很少直接使用第三方包对读取出的配置项的值进行管理。于是我们就面对这样一个问题:其他包如果要使用这些被读取出的配置项的值该如何做呢?我们以读取ini格式承载的配置文件为例,来简单说说。

1. 全局变量法

这是最粗糙的方法,但却是最易理解的方法。我们建立一个config包,在main函数中读取配置文件并将读取到的配置项信息存放在config包的一个导出的全局变量中,这样其他包要想获取配置文件中配置项的信息,直接通过该全局变量读取即可。下面的demo1就是一个使用全局变量组织读取出的配置项信息的示例项目,其代码结构如下:

// github.com/bigwhite/experiments/tree/master/read-ini/demo1

demo1
├── conf
│   └── demo.ini
├── go.mod
├── go.sum
├── main.go
└── pkg
    ├── config
    │   └── config.go
    └── pkg1
        └── pkg1.go

demo1中的conf/demo.ini中存储了下面这些配置项信息:

$cat demo.ini
[server]
id = 100001
port = 23333
tls_port = 83333

[log]
level = 0; info:0, warn: 1, error: 2, dpanic:3, panic:4, fatal: 5, debug: -1
compress = true ; indicate whether the rotated log files should be compressed using gzip (default true)
path = "./log/demo.log" ; if it is empty, we use default logger(to stderr)
max_age = 3 ; the maximum number of days to retain old log files based on the timestamp encoded in their filename
maxbackups = 7 ; the maximum number of old log files to retain (default 7)
maxsize = 100 ; the maximum size in megabytes of the log file before it gets rotated (default 100)

[debug]
profile_on = true ;add profile web server for app to enable pprof through web
profile_port = 8091 ; profile web port

我们通过config包读取该配置文件(基于github.com/go-ini/ini包实现ini配置文件读取):

// github.com/bigwhite/experiments/tree/master/read-ini/demo1/pkg/config/config.go
package config

import (
    ini "github.com/go-ini/ini"
)

type Server struct {
    Id      string `ini:""`
    Port    int    `ini:"port"`
    TlsPort int    `ini:"tls_port"`
}

type Log struct {
    Compress   bool   `ini:"compress"`
    LogPath    string `ini:"path"`
    MaxAge     int    `ini:"max_age"`
    MaxBackups int    `ini:"maxbackups"`
    MaxSize    int    `ini:"maxsize"`
}

type Debug struct {
    ProfileOn   bool   `ini:"profile_on"`
    ProfilePort string `ini:"profile_port"`
}

type IniConfig struct {
    Server `ini:"server"`
    Log    `ini:"log"`
    Debug  `ini:"debug"`
}

var Config = &IniConfig{}

func InitFromFile(path string) error {
    cfg, err := ini.Load(path)
    if err != nil {
        return err
    }

    return cfg.MapTo(Config)
}

这是一种典型的Go通过struct field tag与ini配置文件中section和key绑定读取的示例,我们在main包中调用InitFromFile读取ini配置文件:

// github.com/bigwhite/experiments/tree/master/read-ini/demo1/main.go

package main

import (
    "github.com/bigwhite/readini/pkg/config"
    "github.com/bigwhite/readini/pkg/pkg1"
)

func main() {
    err := config.InitFromFile("conf/demo.ini")
    if err != nil {
        panic(err)
    }
    pkg1.Foo()
}

读取后的配置项信息存储在config.Config这个全局变量中。在其他包中(比如pkg/pkg1/pkg1.go),我们可直接访问该全局变量获取配置项信息:

// github.com/bigwhite/experiments/tree/master/read-ini/demo1/pkg/pkg1/pkg1.go
package pkg1

import (
    "fmt"

    "github.com/bigwhite/readini/pkg/config"
)

func Foo() {
    fmt.Printf("%#v\n", config.Config)
}

这种方式很简单、直观也易于理解,但以全局变量形式将配置项信息暴露给其他包,从代码设计层面,这总是会予人口实的。那么我们是否可以只暴露包函数,而不暴露具体实现呢?

2. 通过section.key形式读取配置项

由于是采用的tag与结构体字段的绑定方法,实际配置项名字与绑定的字段名字可能是不一致的,比如下面代码段中的结构体字段TlsPort与其tag tls_port:

type Server struct {
    Id      string `ini:"id"`
    Port    int    `ini:"port"`
    TlsPort int    `ini:"tls_port"`
}

这样使用config包的用户在要获取配置项值时就必须了解绑定的结构体字段的名字。如果我们不暴露这些绑定结构体的实现细节的话,config包的用户所掌握的信息仅仅就是配置文件(比如:demo.ini)本身了。

于是一个很自然的想法就会萌发出来!我们是否可以通过section.key的形式得到对应配置项的值,比如以下面配置项为例:

[server]
id = 100001
port = 23333
tls_port = 83333

我们需要通过server.id来获得id这个配置项的值,类似的其他配置项的获取方式是传入server.port、server.tls_port等。这样我们的config包仅需保留类似一个接收xx.yy.zz为参数的GetSectionKey函数即可,就像下面这样:

id, ok := config.GetSectionKey("server.id")

接下来,我们就沿着这个思路在demo1的基础上重构为新方案demo2。下面是修改后的demo2的config包代码:

// github.com/bigwhite/experiments/tree/master/read-ini/demo2/pkg/config/config.go
package config

import (
    "reflect"
    "strings"

    ini "github.com/go-ini/ini"
)

type server struct {
    Id      string `ini:"id"`
    Port    int    `ini:"port"`
    TlsPort int    `ini:"tls_port"`
}

type log struct {
    Compress   bool   `ini:"compress"`
    LogPath    string `ini:"path"`
    MaxAge     int    `ini:"max_age"`
    MaxBackups int    `ini:"maxbackups"`
    MaxSize    int    `ini:"maxsize"`
}

type debug struct {
    ProfileOn   bool   `ini:"profile_on"`
    ProfilePort string `ini:"profile_port"`
}

type iniConfig struct {
    Server server `ini:"server"`
    Log    log    `ini:"log"`
    Dbg    debug  `ini:"debug"`
}

var thisConfig = iniConfig{}

func InitFromFile(path string) error {
    cfg, err := ini.Load(path)
    if err != nil {
        return err
    }

    return cfg.MapTo(&thisConfig)
}

func GetSectionKey(name string) (interface{}, bool) {
    keys := strings.Split(name, ".")
    lastKey := keys[len(keys)-1]
    v := reflect.ValueOf(thisConfig)
    t := reflect.TypeOf(thisConfig)

    found := false
    for _, key := range keys {
        cnt := v.NumField()

        for i := 0; i < cnt; i++ {
            field := t.Field(i)
            if field.Tag.Get("ini") == key {
                t = field.Type
                v = v.Field(i)
                if key == lastKey {
                    found = true
                }
                break
            }
        }
    }

    if found {
        return v.Interface(), true
    }
    return nil, false
}

我们将原先暴露出去的全局变量改为了包内变量(thisConfig),几个绑定的结构体类型也都改为非导出的了。我们提供了一个对外的函数:GetSectionKey,这样通过该函数,我们就可以使用section.key的形式获取到对应配置项的值了。在GetSectionKey函数的实现中,我们使用了反射来获取结构体定义中各个字段的tag来和传入的section.key的各个部分做比对,一旦匹配,便将对应的值传出来。如果没有匹配到,则返回false,这里GetSectionKey的返回值列表设计也使用了经典的“comma, ok”模式。

这样,我们在pkg1包中便可以这样来获取对应的配置项的值了:

// github.com/bigwhite/experiments/tree/master/read-ini/demo2/pkg/pkg1/pkg1.go
package pkg1

import (
    "fmt"

    "github.com/bigwhite/readini/pkg/config"
)

func Foo() {
    id, ok := config.GetSectionKey("server.id")
    fmt.Printf("id = [%v], ok = [%t]\n", id, ok)
    tlsPort, ok := config.GetSectionKey("server.tls_port")
    fmt.Printf("tls_port = [%v], ok = [%t]\n", tlsPort, ok)
    logPath, ok := config.GetSectionKey("log.path")
    fmt.Printf("path = [%v], ok = [%t]\n", logPath, ok)
    logPath1, ok := config.GetSectionKey("log.path1")
    fmt.Printf("path1 = [%v], ok = [%t]\n", logPath1, ok)
}

运行demo2,我们将看到如下结果:

$go run main.go
id = [100001], ok = [true]
tls_port = [83333], ok = [true]
path = [./log/demo.log], ok = [true]
path1 = [<nil>], ok = [false]

现在还有一个问题,那就是config包暴露的函数GetSectionKey的第一个返回值类型为interface{},这样我们得到配置项的值后还得根据其类型通过类型断言方式进行转型,体验略差,我们可以在config包中提供常见类型的“语法糖”函数,比如下面这些:

// github.com/bigwhite/experiments/tree/master/read-ini/demo2/pkg/config/config.go
func GetInt(name string) (int, bool) {
    i, ok := GetSectionKey(name)
    if !ok {
        return 0, false
    }

    if v, ok := i.(int); ok {
        return v, true
    }

    // maybe it is a digital string
    s, ok := i.(string)
    if !ok {
        return 0, false
    }

    n, err := strconv.Atoi(s)
    if err != nil {
        return 0, false
    }
    return n, true
}

func GetString(name string) (string, bool) {
    i, ok := GetSectionKey(name)
    if !ok {
        return "", false
    }

    s, ok := i.(string)
    if !ok {
        return "", false
    }
    return s, true
}

func GetBool(name string) (bool, bool) {
    i, ok := GetSectionKey(name)
    if !ok {
        return false, false
    }

    b, ok := i.(bool)
    if !ok {
        return false, false
    }
    return b, true
}

这样我们在pkg1包中就可以直接使用这些语法糖函数获取对应类型的配置项值了:

// github.com/bigwhite/experiments/tree/master/read-ini/demo2/pkg/pkg1/pkg1.go
b, ok := config.GetBool("debug.profile_on")
fmt.Printf("profile_on = [%t], ok = [%t]\n", b, ok)

3. 优化

配置读取一般都是在系统初始化阶段,对其性能要求不高。后续系统运行过程中,也会偶有获取配置项的业务逻辑。一旦在关键路径上有获取配置项值的逻辑,上面的方案便值得商榷,因为每次通过GetSectionKey获取一个配置项的值都要通过反射进行一番操作,性能肯定不佳。

那么如何优化呢?我们可以通过为每个key建立索引来进行。我们在config包中创建一个除初始化时只读的map变量:

// github.com/bigwhite/experiments/tree/master/read-ini/demo3/pkg/config/config.go
var index = make(map[string]interface{}, 100)

在config包的InitFromFile中我们将配置项以section.key为key的形式索引到该index变量中:

// github.com/bigwhite/experiments/tree/master/read-ini/demo3/pkg/config/config.go

func InitFromFile(path string) error {
    cfg, err := ini.Load(path)
    if err != nil {
        return err
    }

    err = cfg.MapTo(&thisConfig)
    if err != nil {
        return err
    }

    createIndex()
    return nil
}

createIndex的实现如下:

// github.com/bigwhite/experiments/tree/master/read-ini/demo3/pkg/config/config.go
func createIndex() {
    v := reflect.ValueOf(thisConfig)
    t := reflect.TypeOf(thisConfig)
    cnt := v.NumField()
    for i := 0; i < cnt; i++ {
        fieldVal := v.Field(i)
        if fieldVal.Kind() != reflect.Struct {
            continue
        }

        // it is a struct kind field, go on to get tag
        fieldStructTyp := t.Field(i)
        tag := fieldStructTyp.Tag.Get("ini")
        if tag == "" {
            continue // no ini tag, ignore it
        }

        // append Field Recursively
        appendField(tag, fieldVal)
    }
}

func appendField(parentTag string, v reflect.Value) {
    cnt := v.NumField()
    for i := 0; i < cnt; i++ {
        fieldVal := v.Field(i)
        fieldTyp := v.Type()
        fieldStructTyp := fieldTyp.Field(i)
        tag := fieldStructTyp.Tag.Get("ini")
        if tag == "" {
            continue
        }
        if fieldVal.Kind() != reflect.Struct {
            // leaf field,  add to map
            index[parentTag+"."+tag] = fieldVal.Interface()
        } else {
            // recursive call appendField
            appendField(parentTag+"."+tag, fieldVal)
        }
    }
}

这样我们的GetSectionKey就会变得异常简单:

func GetSectionKey(name string) (interface{}, bool) {
    v, ok := index[name]
    return v, ok
}

我们看到:每次调用config.GetSectionKey将变成一次map的查询操作,这性能那是相当的高:)。

4. 第三方方案

其实前面那些仅仅是一个配置项读取思路的演进过程,你完全无需自行实现,因为我们有实现的更好的第三方包可以直接使用,比如viper。我们用viper来替换demo3中的config包,代码见demo4:

// github.com/bigwhite/experiments/tree/master/read-ini/demo4/main.go
package main

import (
    "github.com/bigwhite/readini/pkg/pkg1"
    "github.com/spf13/viper"
)

func main() {
    viper.SetConfigName("demo")
    viper.SetConfigType("ini")
    viper.AddConfigPath("./conf")
    err := viper.ReadInConfig()
    if err != nil {
        panic(err)
    }
    pkg1.Foo()
}

我们在main函数中利用viper的API读取demo.ini中的配置。然后在pkg1.Foo函数中向下面这样获取配置项的值即可:

// github.com/bigwhite/experiments/tree/master/read-ini/demo4/pkg/pkg1/pkg1.go
package pkg1

import (
    "fmt"

    "github.com/spf13/viper"
)

func Foo() {
    id := viper.GetString("server.id")
    fmt.Printf("id = [%s]\n", id)
    tlsPort := viper.GetInt("server.tls_port")
    fmt.Printf("tls_port = [%d]\n", tlsPort)

    logPath := viper.GetString("log.path")
    fmt.Printf("path = [%s]\n", logPath)
    if viper.IsSet("log.path1") {
        logPath1 := viper.GetString("log.path1")
        fmt.Printf("path1 = [%s]\n", logPath1)
    } else {
        fmt.Printf("log.path1 is not found\n")
    }
}

上面的实现基本等价于我们在demo3中所作的一切,viper没有使用“comma, ok”模式,我们需要自己调用viper.IsSet来判断是否有某个配置项,而不是通过像GetString这样的函数返回的空字符串来判断。

使用viper后,我们甚至无需创建与配置文件中配置项对应的结构体类型了。viper是一个强大的Go配置操作框架,它能实现的不仅限于上面这些,它还支持写配置文件、监视配置文件变化并热加载、支持多种配置文件类型(JSON, TOML, YAML, HCL, ini等)、支持从环境变量和命令行参数读取配置,并且命令行参数、环境变量、配置文件等究竟以哪个配置为准,viper是按一定优先级次序的,从高到低分别为:

  • 明确调用Set
  • flag
  • env
  • config
  • key/value store
  • default

有如此完善的配置操作第三方库,我们完全无需手动撸自己的实现了。

5. 小结

除了在本文中提供的使用包级API获取配置项值的方法外,我们还可以将读取出的配置项集合放入应用上下文,以参数的形式“传递”到应用的各个角落,但笔者更喜欢向viper这种通过公共函数获取配置项的方法。本文阐述的就是这种思路的演化过程,并给出一个“玩票”的实现(未经系统测试),以帮助大家了解其中原理,但不要将其用到你的项目中哦。

本文涉及的源码请到这里下载:https://github.com/bigwhite/experiments/tree/master/read-ini。


“Gopher部落”知识星球正式转正(从试运营星球变成了正式星球)!“gopher部落”旨在打造一个精品Go学习和进阶社群!高品质首发Go技术文章,“三天”首发阅读权,每年两期Go语言发展现状分析,每天提前1小时阅读到新鲜的Gopher日报,网课、技术专栏、图书内容前瞻,六小时内必答保证等满足你关于Go语言生态的所有需求!部落目前虽小,但持续力很强。在2021年上半年,部落将策划两个专题系列分享,并且是部落独享哦:

  • Go技术书籍的书摘和读书体会系列
  • Go与eBPF系列

欢迎大家加入!

Go技术专栏“改善Go语⾔编程质量的50个有效实践”正在慕课网火热热销中!本专栏主要满足广大gopher关于Go语言进阶的需求,围绕如何写出地道且高质量Go代码给出50条有效实践建议,上线后收到一致好评!欢迎大家订
阅!

img{512x368}

我的网课“Kubernetes实战:高可用集群搭建、配置、运维与应用”在慕课网热卖中,欢迎小伙伴们订阅学习!

img{512x368}

我爱发短信:企业级短信平台定制开发专家 https://tonybai.com/。smspush : 可部署在企业内部的定制化短信平台,三网覆盖,不惧大并发接入,可定制扩展; 短信内容你来定,不再受约束, 接口丰富,支持长短信,签名可选。2020年4月8日,中国三大电信运营商联合发布《5G消息白皮书》,51短信平台也会全新升级到“51商用消息平台”,全面支持5G RCS消息。

著名云主机服务厂商DigitalOcean发布最新的主机计划,入门级Droplet配置升级为:1 core CPU、1G内存、25G高速SSD,价格5$/月。有使用DigitalOcean需求的朋友,可以打开这个链接地址:https://m.do.co/c/bff6eed92687 开启你的DO主机之路。

Gopher Daily(Gopher每日新闻)归档仓库 – https://github.com/bigwhite/gopherdaily

我的联系方式:

  • 微博:https://weibo.com/bigwhite20xx
  • 微信公众号:iamtonybai
  • 博客:tonybai.com
  • github: https://github.com/bigwhite
  • “Gopher部落”知识星球:https://public.zsxq.com/groups/51284458844544

微信赞赏:
img{512x368}

商务合作方式:撰稿、出书、培训、在线课程、合伙创业、咨询、广告合作。

Golang程序配置方案小结

在Twitter上看到一篇关于Golang程序配置方案总结的系列文章(一个mini series,共6篇),原文链接:在这里。我觉得不错,这里粗略整理(非全文翻译)一下,供大家参考。

一、背景

无论使用任何编程语言开发应用,都离不开配置数据。配置数据提供的形式有多样,不外乎命令行选项(options)、参数(parameters),环境 变量(env vars)以及配置文件等。Golang也不例外。Golang内置flag标准库,可以用来支持部分命令行选项和参数的解析;Golang通过os包提 供的方法可以获取当前环境变量;但Golang没有规定标准配置文件格式(虽说内置支持xml、json),多通过第三方 包来解决配置文件读取的问题。Golang配置相关的第三方包邮很多,作者在本文中给出的配置方案中就包含了主流的第三方配置数据操作包。

文章作者认为一个良好的应用配置层次应该是这样的:
1、程序内内置配置项的初始默认值
2、配置文件中的配置项值可以覆盖(override)程序内配置项的默认值。
3、命令行选项和参数值具有最高优先级,可以override前两层的配置项值。

下面就按作者的思路循序渐进探讨golang程序配置方案。

二、解析命令行选项和参数

这一节关注golang程序如何访问命令行选项和参数。

golang对访问到命令行参数提供了内建的支持:

//cmdlineargs.go
package main

import (
    //      "fmt"
    "os"
    "path/filepath"
)

func main() {
    println("I am ", os.Args[0])

    baseName := filepath.Base(os.Args[0])
    println("The base name is ", baseName)

    // The length of array a can be discovered using the built-in function len
    println("Argument # is ", len(os.Args))

    // the first command line arguments
    if len(os.Args) > 1 {
        println("The first command line argument: ", os.Args[1])
    }
}

执行结果如下:
$go build cmdlineargs.go
$cmdlineargs test one
I am  cmdlineargs
The base name is  cmdlineargs
Argument # is  3
The first command line argument:  test

对于命令行结构复杂一些的程序,我们最起码要用到golang标准库内置的flag包:

//cmdlineflag.go
package main

import (
    "flag"
    "fmt"
    "os"
    "strconv"
)

var (
    // main operation modes
    write = flag.Bool("w", false, "write result back instead of stdout\n\t\tDefault: No write back")

    // layout control
    tabWidth = flag.Int("tabwidth", 8, "tab width\n\t\tDefault: Standard")

    // debugging
    cpuprofile = flag.String("cpuprofile", "", "write cpu profile to this file\n\t\tDefault: no default")
)

func usage() {
    // Fprintf allows us to print to a specifed file handle or stream
    fmt.Fprintf(os.Stderr, "\nUsage: %s [flags] file [path ...]\n\n",
        "CommandLineFlag") // os.Args[0]
    flag.PrintDefaults()
    os.Exit(0)
}

func main() {
    fmt.Printf("Before parsing the flags\n")
    fmt.Printf("T: %d\nW: %s\nC: '%s'\n",
        *tabWidth, strconv.FormatBool(*write), *cpuprofile)

    flag.Usage = usage
    flag.Parse()

    // There is also a mandatory non-flag arguments
    if len(flag.Args()) < 1 {
        usage()
    }
   
    fmt.Printf("Testing the flag package\n")
    fmt.Printf("T: %d\nW: %s\nC: '%s'\n",
        *tabWidth, strconv.FormatBool(*write), *cpuprofile)

    for index, element := range flag.Args() {
        fmt.Printf("I: %d C: '%s'\n", index, element)
    }
}

这个例子中:
- 说明了三种类型标志的用法:Int、String和Bool。
- 说明了每个标志的定义都由类型、命令行选项文本、默认值以及含义解释组成。
- 最后说明了如何处理标志选项(flag option)以及非option参数。

不带参数运行:

$cmdlineflag
Before parsing the flags
T: 8
W: false
C: ''

Usage: CommandLineFlag [flags] file [path ...]

  -cpuprofile="": write cpu profile to this file
        Default: no default
  -tabwidth=8: tab width
        Default: Standard
  -w=false: write result back instead of stdout
        Default: No write back

带命令行标志以及参数运行(一个没有flag,一个有两个flag):

$cmdlineflag aa bb
Before parsing the flags
T: 8
W: false
C: ''
Testing the flag package
T: 8
W: false
C: ''
I: 0 C: 'aa'
I: 1 C: 'bb'

$cmdlineflag -tabwidth=2 -w aa
Before parsing the flags
T: 8
W: false
C: ''
Testing the flag package
T: 2
W: true
C: ''
I: 0 C: 'aa'

从例子可以看出,简单情形下,你无需编写自己的命令行parser或使用第三方包,使用go内建的flag包即可以很好的完成工作。但是golang的 flag包与命令行Parser的事实标准:Posix getopt(C/C++/Perl/Shell脚本都可用)相比,还有较大差距,主要体现在:

1、无法支持区分long option和short option,比如:-h和–help。
2、不支持short options合并,比如:ls -l -h <=> ls -hl
3、命令行标志的位置不能任意放置,比如无法放在non-flag parameter的后面。

不过毕竟flag是golang内置标准库包,你无须付出任何cost,就能使用它的功能。另外支持bool型的flag也是其一大亮点。

三、TOML,Go配置文件的事实标准(这个可能不能得到认同)

命令行虽然是一种可选的配置方案,但更多的时候,我们使用配置文件来存储静态的配置数据。就像Java配xml,ruby配yaml,windows配 ini,Go也有自己的搭配组合,那就是TOML(Tom's Obvious, Minimal Language)。

初看toml语法有些类似windows ini,但细致研究你会发现它远比ini强大的多,下面是一个toml配置文件例子:

# This is a TOML document. Boom.

title = "TOML Example"

[owner]
name = "Lance Uppercut"
dob = 1979-05-27T07:32:00-08:00 # First class dates? Why not?

[database]
server = "192.168.1.1"
ports = [ 8001, 8001, 8002 ]
connection_max = 5000
enabled = true

[servers]

  # You can indent as you please. Tabs or spaces. TOML don't care.
  [servers.alpha]
  ip = "10.0.0.1"
  dc = "eqdc10"

  [servers.beta]
  ip = "10.0.0.2"
  dc = "eqdc10"

[clients]
data = [ ["gamma", "delta"], [1, 2] ]

# Line breaks are OK when inside arrays
hosts = [
  "alpha",
  "omega"
]

看起来很强大,也很复杂,但解析起来却很简单。以下面这个toml 文件为例:

Age = 25
Cats = [ "Cauchy", "Plato" ]
Pi = 3.14
Perfection = [ 6, 28, 496, 8128 ]
DOB = 1987-07-05T05:45:00Z

和所有其他配置文件parser类似,这个配置文件中的数据可以被直接解析成一个golang struct:

type Config struct {
  Age int
  Cats []string
  Pi float64
  Perfection []int
  DOB time.Time // requires `import time`
}

其解析的步骤也很简单:

var conf Config
if _, err := toml.Decode(tomlData, &conf); err != nil {
  // handle error
}

是不是简单的不能简单了!

不过toml也有其不足之处。想想如果你需要使用命令行选项的参数值来覆盖这些配置文件中的选项,你应该怎么做?事实上,我们常常会碰到类似下面这种三层配置结构的情况:

1、程序内内置配置项的初始默认值
2、配置文件中的配置项值可以覆盖(override)程序内配置项的默认值。
3、命令行选项和参数值具有最高优先级,可以override前两层的配置项值。

在go中,toml映射的结果体字段没有初始值。而且go内建flag包也没有将命令行参数值解析为一个go结构体,而是零散的变量。这些可以通过第三方工具来解决,但如果你不想用第三方工具,你也可以像下面这样自己解决,虽然难看一些。

func ConfigGet() *Config {
    var err error
    var cf *Config = NewConfig()

    // set default values defined in the program
    cf.ConfigFromFlag()
    //log.Printf("P: %d, B: '%s', F: '%s'\n", cf.MaxProcs, cf.Webapp.Path)

    // Load config file, from flag or env (if specified)
    _, err = cf.ConfigFromFile(*configFile, os.Getenv("APPCONFIG"))
    if err != nil {
        log.Fatal(err)
    }
    //log.Printf("P: %d, B: '%s', F: '%s'\n", cf.MaxProcs, cf.Webapp.Path)

    // Override values from command line flags
    cf.ConfigToFlag()
    flag.Usage = usage
    flag.Parse()
    cf.ConfigFromFlag()
    //log.Printf("P: %d, B: '%s', F: '%s'\n", cf.MaxProcs, cf.Webapp.Path)

    cf.ConfigApply()

    return cf
}

就像上面代码中那样,你需要:
1、用命令行标志默认值设置配置(cf)默认值。
2、接下来加载配置文件
3、用配置值(cf)覆盖命令行标志变量值
4、解析命令行参数
5、用命令行标志变量值覆盖配置(cf)值。

少一步你都无法实现三层配置能力。

四、超越TOML

本节将关注如何克服TOML的各种局限。

为了达成这个目标,很多人会说:使用viper,不过在介绍viper这一重量级选手 之前,我要为大家介绍另外一位不那么知名的选手:multiconfig

有些人总是认为大的就是好的,但我相信适合的还是更好的。因为:

1、viper太重量级,使用viper时你需要pull另外20个viper依赖的第三方包
2、事实上,viper单独使用还不足以满足需求,要想得到viper全部功能,你还需要另外一个包配合,而后者又依赖13个外部包
3、与viper相比,multiconfig使用起来更简单。

好了,我们再来回顾一下我们现在面临的问题:

1、在程序里定义默认配置,这样我们就无需再在toml中定义它们了。
2、用toml配置文件中的数据override默认配置
3、用命令行或环境变量的值override从toml中读取的配置。

下面是一个说明如何使用multiconfig的例子:

func main() {
    m := multiconfig.NewWithPath("config.toml") // supports TOML and JSON

    // Get an empty struct for your configuration
    serverConf := new(Server)

    // Populated the serverConf struct
    m.MustLoad(serverConf) // Check for error

    fmt.Println("After Loading: ")
    fmt.Printf("%+v\n", serverConf)

    if serverConf.Enabled {
        fmt.Println("Enabled field is set to true")
    } else {
        fmt.Println("Enabled field is set to false")
    }
}

这个例子中的toml文件如下:

Name              = "koding"
Enabled           = false
Port              = 6066
Users             = ["ankara", "istanbul"]

[Postgres]
Enabled           = true
Port              = 5432
Hosts             = ["192.168.2.1", "192.168.2.2", "192.168.2.3"]
AvailabilityRatio = 8.23

toml映射后的go结构如下:

type (
    // Server holds supported types by the multiconfig package
    Server struct {
        Name     string
        Port     int `default:"6060"`
        Enabled  bool
        Users    []string
        Postgres Postgres
    }

    // Postgres is here for embedded struct feature
    Postgres struct {
        Enabled           bool
        Port              int
        Hosts             []string
        DBName            string
        AvailabilityRatio float64
    }
)

multiconfig的使用是不是很简单,后续与viper对比后,你会同意我的观点的。

multiconfig支持默认值,也支持显式的字段赋值需求。
支持toml、json、结构体标签(struct tags)以及环境变量。
你可以自定义配置源(例如一个远程服务器),如果你想这么做的话。
可高度扩展(通过loader接口),你可以创建你自己的loader。

下面是例子的运行结果,首先是usage help:

$cmdlinemulticonfig -help
Usage of cmdlinemulticonfig:
  -enabled=false: Change value of Enabled.
  -name=koding: Change value of Name.
  -port=6066: Change value of Port.
  -postgres-availabilityratio=8.23: Change value of Postgres-AvailabilityRatio.
  -postgres-dbname=: Change value of Postgres-DBName.
  -postgres-enabled=true: Change value of Postgres-Enabled.
  -postgres-hosts=[192.168.2.1 192.168.2.2 192.168.2.3]: Change value of Postgres-Hosts.
  -postgres-port=5432: Change value of Postgres-Port.
  -users=[ankara istanbul]: Change value of Users.

Generated environment variables:
   SERVER_NAME
   SERVER_PORT
   SERVER_ENABLED
   SERVER_USERS
   SERVER_POSTGRES_ENABLED
   SERVER_POSTGRES_PORT
   SERVER_POSTGRES_HOSTS
   SERVER_POSTGRES_DBNAME
   SERVER_POSTGRES_AVAILABILITYRATIO

$cmdlinemulticonfig
After Loading:
&{Name:koding Port:6066 Enabled:false Users:[ankara istanbul] Postgres:{Enabled:true Port:5432 Hosts:[192.168.2.1 192.168.2.2 192.168.2.3] DBName: AvailabilityRatio:8.23}}
Enabled field is set to false

检查一下输出结果吧,是不是每项都符合我们之前的预期呢!

五、Viper

我们的重量级选手viper(https://github.com/spf13/viper)该出场了!

毫无疑问,viper非常强大。但如果你想用命令行参数覆盖预定义的配置项值,viper自己还不足以。要想让viper爆发,你需要另外一个包配合,它就是cobra(https://github.com/spf13/cobra)。

不同于注重简化配置处理的multiconfig,viper让你拥有全面控制力。不幸的是,在得到这种控制力之前,你需要做一些体力活。

我们再来回顾一下使用multiconfig处理配置的代码:

func main() {
    m := multiconfig.NewWithPath("config.toml") // supports TOML and JSON

    // Get an empty struct for your configuration
    serverConf := new(Server)

    // Populated the serverConf struct
    m.MustLoad(serverConf) // Check for error

    fmt.Println("After Loading: ")
    fmt.Printf("%+v\n", serverConf)

    if serverConf.Enabled {
        fmt.Println("Enabled field is set to true")
    } else {
        fmt.Println("Enabled field is set to false")
    }
}

这就是使用multiconfig时你要做的所有事情。现在我们来看看使用viper和cobra如何来完成同样的事情:

func init() {
    mainCmd.AddCommand(versionCmd)

    viper.SetEnvPrefix("DISPATCH")
    viper.AutomaticEnv()

    /*
      When AutomaticEnv called, Viper will check for an environment variable any
      time a viper.Get request is made. It will apply the following rules. It
      will check for a environment variable with a name matching the key
      uppercased and prefixed with the EnvPrefix if set.
    */

    flags := mainCmd.Flags()

    flags.Bool("debug", false, "Turn on debugging.")
    flags.String("addr", "localhost:5002", "Address of the service")
    flags.String("smtp-addr", "localhost:25", "Address of the SMTP server")
    flags.String("smtp-user", "", "User to authenticate with the SMTP server")
    flags.String("smtp-password", "", "Password to authenticate with the SMTP server")
    flags.String("email-from", "noreply@example.com", "The from email address.")

    viper.BindPFlag("debug", flags.Lookup("debug"))
    viper.BindPFlag("addr", flags.Lookup("addr"))
    viper.BindPFlag("smtp_addr", flags.Lookup("smtp-addr"))
    viper.BindPFlag("smtp_user", flags.Lookup("smtp-user"))
    viper.BindPFlag("smtp_password", flags.Lookup("smtp-password"))
    viper.BindPFlag("email_from", flags.Lookup("email-from"))

  // Viper supports reading from yaml, toml and/or json files. Viper can
  // search multiple paths. Paths will be searched in the order they are
  // provided. Searches stopped once Config File found.

    viper.SetConfigName("CommandLineCV") // name of config file (without extension)
    viper.AddConfigPath("/tmp")          // path to look for the config file in
    viper.AddConfigPath(".")             // more path to look for the config files

    err := viper.ReadInConfig()
    if err != nil {
        println("No config file found. Using built-in defaults.")
    }
}

可以看出,你需要使用BindPFlag来让viper和cobra结合一起工作。但这还不算太糟。

cobra的真正威力在于提供了subcommand能力。同时cobra还提供了与posix 全面兼容的命令行标志解析能力,包括长短标志、内嵌命令、为command定义你自己的help或usage等。

下面是定义子命令的例子代码:

// The main command describes the service and defaults to printing the
// help message.
var mainCmd = &cobra.Command{
    Use:   "dispatch",
    Short: "Event dispatch service.",
    Long:  `HTTP service that consumes events and dispatches them to subscribers.`,
    Run: func(cmd *cobra.Command, args []string) {
        serve()
    },
}

// The version command prints this service.
var versionCmd = &cobra.Command{
    Use:   "version",
    Short: "Print the version.",
    Long:  "The version of the dispatch service.",
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println(version)
    },
}

有了上面subcommand的定义,我们就可以得到如下的help信息了:

Usage:
  dispatch [flags]
  dispatch [command]

Available Commands:
  version     Print the version.
  help        Help about any command

Flags:
      –addr="localhost:5002": Address of the service
      –debug=false: Turn on debugging.
      –email-from="noreply@example.com": The from email address.
  -h, –help=false: help for dispatch
      –smtp-addr="localhost:25": Address of the SMTP server
      –smtp-password="": Password to authenticate with the SMTP server
      –smtp-user="": User to authenticate with the SMTP server

Use "dispatch help [command]" for more information about a command.

六、小结

以上例子的完整源码在作者的github repository里可以找到。

关于golang配置文件,我个人用到了toml这一层次,因为不需要太复杂的配置,不需要环境变量或命令行override默认值或配置文件数据。不过 从作者的例子中可以看到multiconfig、viper的确强大,后续在实现复杂的golang应用时会考虑真正应用。

如发现本站页面被黑,比如:挂载广告、挖矿等恶意代码,请朋友们及时联系我。十分感谢! Go语言第一课 Go语言精进之路1 Go语言精进之路2 商务合作请联系bigwhite.cn AT aliyun.com

欢迎使用邮件订阅我的博客

输入邮箱订阅本站,只要有新文章发布,就会第一时间发送邮件通知你哦!

这里是 Tony Bai的个人Blog,欢迎访问、订阅和留言! 订阅Feed请点击上面图片

如果您觉得这里的文章对您有帮助,请扫描上方二维码进行捐赠 ,加油后的Tony Bai将会为您呈现更多精彩的文章,谢谢!

如果您希望通过微信捐赠,请用微信客户端扫描下方赞赏码:

如果您希望通过比特币或以太币捐赠,可以扫描下方二维码:

比特币:

以太币:

如果您喜欢通过微信浏览本站内容,可以扫描下方二维码,订阅本站官方微信订阅号“iamtonybai”;点击二维码,可直达本人官方微博主页^_^:
本站Powered by Digital Ocean VPS。
选择Digital Ocean VPS主机,即可获得10美元现金充值,可 免费使用两个月哟! 著名主机提供商Linode 10$优惠码:linode10,在 这里注册即可免费获 得。阿里云推荐码: 1WFZ0V立享9折!


View Tony Bai's profile on LinkedIn
DigitalOcean Referral Badge

文章

评论

  • 正在加载...

分类

标签

归档



View My Stats