文章首发于:clawhub.club


使用java的spring的时候,配置文件用的最多的就是properties格式。最近用GO,尝试用一下前人写好的工具,学习。
请配置好GO环境,我这使用的是govendor包管理工具。

magiconair/properties 114颗星

具体详细介绍,请参考github。

安装

1
go get -u github.com/magiconair/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
37
38
39
40
41
42
43
44
45
46
47
48
49
import (
"flag"
"github.com/magiconair/properties"
)

func main() {
// init from a file
p := properties.MustLoadFile("${HOME}/config.properties", properties.UTF8)

// or multiple files
p = properties.MustLoadFiles([]string{
"${HOME}/config.properties",
"${HOME}/config-${USER}.properties",
}, properties.UTF8, true)

// or from a map
p = properties.LoadMap(map[string]string{"key": "value", "abc": "def"})

// or from a string
p = properties.MustLoadString("key=value\nabc=def")

// or from a URL
p = properties.MustLoadURL("http://host/path")

// or from multiple URLs
p = properties.MustLoadURL([]string{
"http://host/config",
"http://host/config-${USER}",
}, true)

// or from flags
p.MustFlag(flag.CommandLine)

// get values through getters
host := p.MustGetString("host")
port := p.GetInt("port", 8080)

// or through Decode
type Config struct {
Host string `properties:"host"`
Port int `properties:"port,default=9000"`
Accept []string `properties:"accept,default=image/png;image;gif"`
Timeout time.Duration `properties:"timeout,default=5s"`
}
var cfg Config
if err := p.Decode(&cfg); err != nil {
log.Fatal(err)
}
}

下面再试一下另一个。

tinyhubs/properties

这个就相对简单了,功能比较单一,参考学习。

使用

  • 直接复制PropertiesDocument.go到本地。
  • 测试
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    fmt.Println("------properties---------")
    //打开文件
    file, err := os.Open("./config.properties")
    if err != nil {
    panic(err)
    }

    /* defer代码块会在函数调用链表中增加一个函数调用。
    * 这个函数调用不是普通的函数调用,而是会在函数正常返回,也就是return之后添加一个函数调用。
    * 因此,defer通常用来释放函数内部变量。
    */
    defer file.Close()

    //加载配置文件
    config, err := document.Load(file)
    if nil != err {
    fmt.Println(err)
    return
    }
    //读取配置
    val := config.String("key")
    fmt.Println("val:" + val)
    config.properties
    1
    key=val

###简单的使用例子

go-study