config

package module
v1.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2020 License: BSD-2-Clause Imports: 2 Imported by: 1

README

go-config:配置文件读取库

go-config 是一个配置文件读取库,用来从约定好的配置文件里读取配置信息,并且反序列化成 Go 的数据结构。

当前只支持 TOML 文件,格式详见 TOML v0.5.0

使用方法

go-config 可以解析约定位置的配置文件。

import "github.com/altstory/go-config"

type MyConfig struct {
    Foo int    `config:"foo"`
    Bar string `config:"bar"`
}

func main() {
    // 假定配置文件 file.conf 内容如下:
    //
    // [my_config]
    // foo = 123
    // bar = "player"

    c, err := config.LoadFile("path/to/config/file.conf")

    if err != nil {
        // 处理错误……
        return
    }

    var myConf MyConfig
    c.Unmarshal("my_config", &myConf)
    fmt.Println(myConf.Foo, myConf.Bar) // 输出:123    player
}

业务代码推荐使用 go-runner 的自动加载机制来加载配置,不要直接使用 go-config 接口。

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config 代表一个配置解析器。

func LoadFile

func LoadFile(path string) (c *Config, err error)

LoadFile 解析指定路径的文件并返回 Config 结构。 当前只支持 toml 格式的配置文件,未来如果有需要再增加其他格式。

func (*Config) LoadExt

func (c *Config) LoadExt(path string) error

LoadExt 加载额外的配置文件,用来覆盖主配置文件, 额外配置与主配置相同的配置项会采用覆盖策略。

额外配置文件有一个特殊字段 `_deletes` 用来删除任意字段。

# 删除配置项 foo 和 bar.player
_deletes = ['foo', 'bar.player']

需要注意,默认覆盖策略是深度合并各种选项,对于数组和对象类型的配置而言, 不会简单替换,而是合并,数组会追加到原数组后,对象会追加更多 key。 如果需要完全替换原来的数组、对象,应该使用 `_deletes` 来删除原来的字段, 再添加新的字段。

func (*Config) Unmarshal

func (c *Config) Unmarshal(section string, v interface{}) error

Unmarshal 反序列化 p 中指定的配置文件。 如果 section 为空,则将整个配置文件反序列化到 v。

需要注意,section 名字中如果含有“.”,会被当做分隔符使用, 例如 http.server,会访问配置文件的 http -> server 的配置内容。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL