fsconf

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2024 License: MIT Imports: 21 Imported by: 3

README

fsconf

1.功能概述

一个可扩展的、简单的配置读取库,默认支持 .json.xml 的配置。

所有以 "#" 开头的行都将认为是注释。

GoDoc

2.对外接口

// 读取并解析配置文件
// confName :相对于 conf/ 目录的文件路径
// 也支持使用绝对路径
Parse(confName string, obj interface{})error

// 使用绝对/相对 读取并解析配置文件
ParseByAbsPath(confAbsPath string, obj interface{})  error

// ParseBytes 解析bytes
// fileExt 是文件后缀,如.json、.toml
ParseBytes(fileExt string,content []byte,obj interface{})error

// 配置文件是否存在
Exists(confName string) bool

// 注册一个指定后缀的配置的parser
// 如要添加 .ini 文件的支持,可在此注册对应的解析函数即可
RegisterParser(fileExt string, fn ParserFn) error

// 注册一个 Hook
RegisterHook(h Helper) error
// NewDefault 创建一个新的配置解析实例
// 会注册默认的配置解析方法和辅助方法
func NewDefault() *Configure 

若对象实现 AutoChecker 接口,当解析完成后会自动调用 AutoCheck 方法

// AutoChecker 当配置解析完成后,用于自动校验
type AutoChecker interface {
	AutoCheck() error
}

3.使用示例

package main

import (
	"fmt"
	"log"

	"github.com/fsgo/fsconf"
)

type Hosts []Host

type Host struct {
	IP   string
	Port int
}

func main() {
	var hs Hosts
    // 默认是从 conf 目录里读取配置
	if err := fsconf.Parse("hosts.json", &hs); err != nil {
		log.Fatal(err)
	}
	
	// 读取当前目录下的 hosts.json
	// fsconf.Parse("./hosts.json", &hs)
	
	// 读取上级目录的 hosts.json
	// fsconf.Parse("../hosts.json", &hs)

	fmt.Println("hosts:", hs)
}

4.特性说明

4.1 扩展能力

为了减少依赖,默认只支持 .json.xml 后缀格式的文件解析,.toml.yml文件格式的支持放在单独的子 module 中。 同时默认的 Validator 也未初始化,即默认为 nil。 若需要使用,可以导入 confext 子模块:

import "github.com/fsgo/fsconf/confext"

func init(){
	confext.Init()
}

导入后,默认的 Validator 会被替换为 github.com/go-playground/validator/v10

4.2 hook:从系统环境变量读取变量

配置内容:

# 若环境变量里有 server_port,而且不为空,则使用环境变量的值,否则使用默认值8080
port = "{osenv.server_port|8080}"

port2 = "{osenv.server_port2}"

这样就可以在运行前通过设置环境变量来影响配置文件:

export  server_port=80
go run main.go
4.3 设置配置读取路径

考虑到不同子模块读取配置的目录可能不同,允许让模块自己设置读取配置文件的根目录。

conf:=fsconf.NewDefault()
env:=fsenv.NewAppEnv(fsenv.Value{RootDir:"./testdata/"})
conf.SetEnv(env)
// your code
var confData map[string]string
conf.Parse("abc.json",&confData)
4.4 .json 格式配置

配置注释:每行以#开头的是注释,在解析时会忽略掉,如:

{
    "ID": 1
#这是注释
   # 这也是注释
}
4.5 hook:从 appenv 读取变量
# 补充上 app 的log 目录的路径
LogFilePath = "{fsenv.LogRootDir}/http/access.log"

支持: {fsenv.RootDir}{fsenv.IDC}{fsenv.DataRootDir}{fsenv.ConfRootDir}{fsenv.LogRootDir}{fsenv.RunMode} 。 不支持其他的 key,否则将报错

4.6 hook:使用 template 能力

该功能默认不开启,需要在文件头部以注释形式声明启用。

# hook.template  Enable=true
1. 表达式

支持使用 template 表达式: https://pkg.go.dev/text/template
额外扩展新增了如下函数:

// 包含子文件,支持一个或子目录下多个文件
// 若文件不存在,会报错
"include": func(name string) (string, error) {
    return h.fnInclude(ctx, name, hp, tp)
},


"osenv": func(name string) string {
    return os.Getenv(name)
},

"contains": func(s string, sub string) bool {
    return strings.Contains(s, sub)
},

"prefix": func(s string, prefix string) bool {
    return strings.HasPrefix(s, prefix)
},

"suffix": func(s string, suffix string) bool {
    return strings.HasSuffix(s, suffix)
},

内置如下变量:

data["IDC"]          = ce.IDC()
data["RootDir"]      = ce.RootDir()
data["ConfRootDir"]  = ce.ConfRootDir()
data["LogRootDir"]   = ce.LogRootDir()
data["DataRootDir"]  = ce.DataRootDir()
data["RunMode"]      = string(ce.RunMode())
2. 示例

如 a.toml 文件内容:

# hook.template  Enable=true
A="123"

{{ include "sub/*.toml" }}

# 若当前 IDC 是 bj,则会输出 IDC 字段
{{ if eq .IDC "bj" }}
IDC="bj"
{{ end }}

sub/b.toml 文件内容:

B=100

最终等效于(a.toml):

# hook.template  Enable=true
A="123"

B=100

IDC="bj"

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Exists

func Exists(confName string) bool

Exists (全局)判断是否存在

confName 的文件后缀是可选的,当查找文件不存在时,会添加上支持的后缀依次去判断。
如 Exists("app.toml") 会去 {ConfDir}/app.toml 判断

func MustParse added in v0.4.0

func MustParse(confName string, obj any)

MustParse 调用 Parse,若返回 err!=ni 则 panic

func MustParseByAbsPath added in v0.4.0

func MustParseByAbsPath(confAbsPath string, obj any)

MustParseByAbsPath 调用 ParseByAbsPath,若返回 err!=ni 则 panic

func MustParseBytes added in v0.4.0

func MustParseBytes(fileExt string, content []byte, obj any)

MustParseBytes 调用 ParseBytes,若返回 err!=ni 则 panic

func MustRegisterHook added in v0.3.0

func MustRegisterHook(h Hook)

MustRegisterHook (全局)注册一个辅助类,若失败会 panic

func MustRegisterParser added in v0.4.0

func MustRegisterParser(fileExt string, fn DecoderFunc)

MustRegisterParser 调用 RegisterParser,若返回的 err!=nil 则 panic

func Parse

func Parse(confName string, obj any) (err error)

Parse 解析配置,配置文件默认认为在 conf/目录下, 如 有 conf/abc.toml ,则 confName="abc.toml"

func ParseByAbsPath

func ParseByAbsPath(confAbsPath string, obj any) (err error)

ParseByAbsPath 解析绝对路径的配置

func ParseBytes added in v0.2.0

func ParseBytes(fileExt string, content []byte, obj any) error

ParseBytes (全局)解析 bytes fileExt 是文件后缀,如.json、.toml

Example
package main

import (
	"fmt"
	"log"

	"github.com/fsgo/fsconf"
)

func main() {
	type User struct {
		Name string
		Age  int
	}
	content := []byte(`{"Name":"Hello","age":18}`)

	var user *User
	if err := fsconf.ParseBytes(".json", content, &user); err != nil {
		log.Fatalln("ParseBytes with error:", err)
	}
	fmt.Println("Name=", user.Name)
	fmt.Println("Age=", user.Age)
}
Output:

Name= Hello
Age= 18

func RegisterHook added in v0.3.0

func RegisterHook(h Hook) error

RegisterHook (全局)注册一个辅助类

func RegisterParser

func RegisterParser(fileExt string, fn DecoderFunc) error

RegisterParser (全局)注册一个解析器 fileExt 是文件后缀,如 .json

Types

type AutoChecker added in v0.2.5

type AutoChecker interface {
	AutoCheck() error
}

AutoChecker 当配置解析完成后,用于自动校验, 这个方法是在 validator 校验完成之后才执行的

type Configure added in v0.2.0

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

func Default

func Default() *Configure

Default 默认的实例

func New

func New() *Configure

New 创建一个新的配置解析实例 返回的实例是没有注册任何解析能力的

func NewDefault

func NewDefault() *Configure

NewDefault 创建一个新的配置解析实例 会注册默认的配置解析方法和辅助方法

func SetDefault added in v0.3.0

func SetDefault(cfg *Configure) (old *Configure)

func WithContext added in v0.2.0

func WithContext(ctx context.Context) *Configure

WithContext (全局)返回新的对象,并设置新的 ctx

func WithHook added in v0.3.0

func WithHook(hs ...Hook) *Configure

WithHook (全局)返回新的对象,并注册 Hook

func (*Configure) Clone added in v0.3.0

func (c *Configure) Clone() *Configure

func (*Configure) Exists added in v0.2.0

func (c *Configure) Exists(confName string) bool

func (*Configure) MustRegisterHook added in v0.3.0

func (c *Configure) MustRegisterHook(h Hook)

MustRegisterHook 注册新的 Hook, 若失败会 panic

func (*Configure) Parse added in v0.2.0

func (c *Configure) Parse(confName string, obj any) (err error)

func (*Configure) ParseByAbsPath added in v0.2.0

func (c *Configure) ParseByAbsPath(confAbsPath string, obj any) (err error)

func (*Configure) ParseBytes added in v0.2.0

func (c *Configure) ParseBytes(fileExt string, content []byte, obj any) error

func (*Configure) RegisterHook added in v0.2.2

func (c *Configure) RegisterHook(h Hook) error

RegisterHook 注册新的 Hook,若出现重名会注册失败

func (*Configure) RegisterParser added in v0.2.0

func (c *Configure) RegisterParser(fileExt string, fn DecoderFunc) error

func (*Configure) WithContext added in v0.2.0

func (c *Configure) WithContext(ctx context.Context) *Configure

func (*Configure) WithHook added in v0.3.0

func (c *Configure) WithHook(hs ...Hook) *Configure

type DecoderFunc added in v0.4.0

type DecoderFunc func(bf []byte, obj any) error

DecoderFunc 针对特定文件后缀的配置解析方法 当前已经内置了 .toml 和 .json的解析方法

type Hook added in v0.2.2

type Hook interface {
	// Name 名称,不可为空
	// 每个 Hook 应返回唯一的名称,若重名会注册失败
	Name() string

	// Execute 对读取的配置内容加工的逻辑
	Execute(ctx context.Context, p *HookParam) (output []byte, err error)
}

Hook 辅助类,在执行解析前,会先会配置的内容进行解析处理

type HookParam added in v0.2.2

type HookParam struct {
	FileExt   string     // 文件类型后缀,如 .toml,.json
	Configure *Configure // 当前 Configure 对象
	ConfPath  string     // 文件路径。当直接解析内容时,为空字符串
	Content   []byte     // 文件内容
}

HookParam param for Hook

type HookTPL added in v0.3.0

type HookTPL struct {
	// HookName 名称,必填
	HookName string

	// KeyPrefix 查找的表达式前缀,必填
	// 最终表达是为  {$RegexpKey.([A-Za-z0-9_]+)}
	KeyPrefix string

	// Values 用于查找的值,必填
	Values map[string]string
	// contains filtered or unexported fields
}

HookTPL 一个通用的可用于替换内容的 Hook 模版

func (*HookTPL) Execute added in v0.3.0

func (h *HookTPL) Execute(ctx context.Context, p *HookParam) (output []byte, err error)

func (*HookTPL) Name added in v0.3.0

func (h *HookTPL) Name() string

type Validator added in v0.2.5

type Validator interface {
	Validate(val any) error
}

Validator 自动规则校验器

默认使用的 github.com/go-playground/validator/v10 如下设置所有字段都是必填的:

type Address struct {
	Street string `validate:"required"`
	City   string `validate:"required"`
	Planet string `validate:"required"`
	Phone  string `validate:"required"`
}
var DefaultValidator Validator

Directories

Path Synopsis
confext module
internal

Jump to

Keyboard shortcuts

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