Documentation
¶
Overview ¶
Package conf 提供读取属性列表的方法,并且通过扩展机制支持各种格式的属性文件。
Index ¶
- Variables
- func Convert(fn interface{})
- func NewReader(r Reader, ext ...string)
- type BindOption
- type GetOption
- type Properties
- func (p *Properties) Bind(i interface{}, opts ...BindOption) error
- func (p *Properties) Get(key string, opts ...GetOption) interface{}
- func (p *Properties) Keys() []string
- func (p *Properties) Load(file string) error
- func (p *Properties) Read(b []byte, ext string) error
- func (p *Properties) Resolve(s string) (string, error)
- func (p *Properties) Set(key string, val interface{})
- type Reader
Constants ¶
This section is empty.
Variables ¶
var (
ErrNotExist = errors.New("not exist")
)
Functions ¶
Types ¶
type BindOption ¶
type BindOption func(arg *bindArg)
type Properties ¶
type Properties struct {
// contains filtered or unexported fields
}
Properties 提供创建和读取属性列表的方法。它使用扁平的 map[string]string 结 构存储数据,属性的 key 可以是 a.b.c 或者 a[0].b 两种形式,a.b.c 表示从 map 结构中获取属性值,a[0].b 表示从切片结构中获取属性值,并且 key 是大小写敏感的。
func Load ¶
func Load(file string) (*Properties, error)
Load 返回一个由属性文件创建的属性列表,file 可以是绝对路径,也可以是相对路径。
func Read ¶
func Read(b []byte, ext string) (*Properties, error)
Read 返回一个由 []byte 创建的属性列表,ext 是文件扩展名,如 .yaml、.toml 等。
func (*Properties) Bind ¶
func (p *Properties) Bind(i interface{}, opts ...BindOption) error
Bind 将 key 对应的属性值绑定到某个数据类型的实例上。i 必须是一个指针,只有这 样才能将修改传递出去。Bind 方法使用 tag 字符串对数据实例进行属性绑定,其语法 为 value:"${a:=b}",其中 value 表示属性绑定,${} 表示属性引用,a 表示属性 的名称,:=b 表示为属性设置默认值。而且 tag 字符串还支持在默认值中进行嵌套引用 ,即 ${a:=${b}}。当然,还有两点需要特别说明: 一是对 array、slice、map、struct 这些复合类型不能设置非空默认值,因为如果 默认值太长会影响阅读体验,而且解析起来也并不容易; 二是可以省略属性名而只有默认值,即 ${:=b},原因是某些情况下属性名可能没想好或 者不太重要,比如,得益于字符串差值的实现,这种语法可以用于动态生成新的属性值, 也有人认为这是一种对 Golang 缺少默认值语法的补充,Bug is Feature。
func (*Properties) Get ¶
func (p *Properties) Get(key string, opts ...GetOption) interface{}
Get 获取 key 对应的属性值,注意 key 是大小写敏感的。当 key 对应的属性值存在时, 或者 key 对应的属性值不存在但设置了默认值时,Get 方法返回 string 类型的数据, 当 key 对应的属性值不存在且没有设置默认值时 Get 方法返回 nil。因此可以通过判断 Get 方法的返回值是否为 nil 来判断 key 对应的属性值是否存在。
func (*Properties) Load ¶
func (p *Properties) Load(file string) error
Load 从属性文件加载属性列表,file 可以是绝对路径,也可以是相对路径。该方法会覆盖 已有的属性值。
func (*Properties) Read ¶
func (p *Properties) Read(b []byte, ext string) error
Read 从 []byte 加载属性列表,ext 是文件扩展名,如 .yaml、.toml 等。该方法会覆 盖已有的属性值。
func (*Properties) Resolve ¶
func (p *Properties) Resolve(s string) (string, error)
Resolve 解析字符串中包含的所有属性引用即 ${key:=def} 的内容,并且支持递归引用。
func (*Properties) Set ¶
func (p *Properties) Set(key string, val interface{})
Set 设置 key 对应的属性值,如果 key 对应的属性值已经存在则 Set 方法会覆盖旧 值。Set 方法除了支持 string 类型的属性值,还支持 int、uint、bool 等其他基础 数据类型的属性值。特殊情况下,Set 方法也支持 slice 、map 与基础数据类型组合构 成的属性值,其处理方式是将组合结构层层展开,可以将组合结构看成一棵树,那么叶子结 点的路径就是属性的 key,叶子结点的值就是属性的值。