gviper

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2024 License: MIT Imports: 7 Imported by: 1

README

gviper

gviper 是一个基于 Viper 的 Golang 配置管理库,提供了更加便捷的多配置文件加载、环境变量绑定、配置动态更新等功能。gviper 支持 YAML、JSON、TOML 等多种配置文件格式,并允许用户通过监听器在配置变化时触发相应的处理逻辑。

功能特性

  • 支持多个配置文件:允许同时加载和监听多个配置文件
  • 动态配置加载:支持配置文件的动态加载与更新。
  • 配置解析:结构化绑定配置到Go结构体
  • 配置变更监听:支持在配置文件发生变化时触发自定义回调。
  • 通知机制:在配置加载或更新失败时,发送通知。
  • 多种配置文件格式支持:支持 YAML、JSON、TOML 等格式。
  • 环境变量支持:自动绑定环境变量,支持自定义环境变量前缀。

安装

使用 go get 命令安装 gviper

go get github.com/ace-zhaoy/gviper

使用示例

基本使用
import (
    "fmt"
    "github.com/ace-zhaoy/gviper"
)

func main() {
    // 当前目录下的 app.yaml、database.json、log.toml 三个文件
    config := gviper.NewConfig(".", "app", "database.json", "log.toml")
    
    // 加载配置文件
    if err := config.Load(); err != nil {
        panic(err)
    }

    // 读取配置项
    fmt.Println("App Name:", config.GetString("app.name"))
    fmt.Println("Database Port:", config.GetInt("database.port"))
    fmt.Println("Log Level:", config.GetString("log.level"))
}
配置文件热加载
// 监听配置文件变化(非阻塞)
config.Watch()
绑定配置到结构体
import (
	"fmt"
	"github.com/ace-zhaoy/gviper"
)

type LogConfig struct {
	Type  string `json:"type"`
	Level string `json:"level"`
}

func main() {
	// 当前目录下的 app.yaml、database.json、log.toml 三个文件
	config := gviper.NewConfig(".", "app", "database.json", "log.toml")

	// 绑定结构体
	var lc LogConfig
	config.Bind("log", &lc)

	// 加载配置文件
	if err := config.Load(); err != nil {
		panic(err)
	}
	
	// 读取配置项
	fmt.Println("Log Level:", lc.Level)
}
注册配置变更监听器
import (
	"fmt"
	"github.com/ace-zhaoy/gviper"
	"github.com/spf13/viper"
)

func main() {
	// 当前目录下的 app.yaml、database.json、log.toml 三个文件
	config := gviper.NewConfig(".", "app", "database.json", "log.toml")

	config.OnChange("database", func(viper *viper.Viper) error {
		fmt.Println("database config changed!")
		fmt.Println("database init success!")
		return nil
	})

	// 加载配置文件
	if err := config.Load(); err != nil {
		panic(err)
	}

	// 监听配置文件变化
	config.Watch()
}
注册通知机制

import (
	"fmt"
	"github.com/ace-zhaoy/gviper"
)

type MyNotification struct{}

func (m *MyNotification) Notify(configName string, err error) {
	// 配置热更新失败
	fmt.Printf(" Config %s reload failed: %v\n", configName, err)
}

func main() {
	// 当前目录下的 app.yaml、database.json、log.toml 三个文件
	config := gviper.NewConfig(".", "app", "database.json", "log.toml")

	notification := &MyNotification{}
	config.RegisterNotification(notification)

	if err := config.Load(); err != nil {
		panic(err)
	}

	// 监听配置文件变化
	config.Watch()
}

环境变量自动绑定
import (
	"fmt"
	"github.com/ace-zhaoy/gviper"
)

func main() {
	// 当前目录下的 app.yaml、database.json、log.toml 三个文件
	config := gviper.NewConfig(".", "app", "database.json", "log.toml")

	// 自动绑定环境变量
	config.AutomaticEnv()

	if err := config.Load(); err != nil {
		panic(err)
	}
	fmt.Println(config.GetString("HOME"))
}
通过 Option 初始化
import (
	"github.com/ace-zhaoy/gviper"
)

func main() {
	// 当前目录下的 app.ini、database.json、log.toml 三个文件
	config := gviper.NewConfigWithOptions(
		gviper.WithConfigPath("."),
		gviper.WithDefaultConfigType("ini"),
	)
	
	// app.ini、database.json、log.toml
	config.Register("app", "database.json", "log.toml")

	if err := config.Load(); err != nil {
		panic(err)
	}

	// 监听配置文件变化
	config.Watch()
}

Documentation

Index

Examples

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
}

func Default added in v1.0.3

func Default(configPath string) *Config

func NewConfig

func NewConfig(configPath string, names ...string) *Config
Example
package main

import (
	"github.com/ace-zhaoy/gviper"
)

func main() {
	config := gviper.NewConfig(".", "app", "database.json", "log.toml")

	// 加载配置文件
	if err := config.Load(); err != nil {
		panic(err)
	}

	// 监听配置文件变化(非阻塞)
	config.Watch()

	_ = config.GetString("app.name")
	_ = config.GetInt("database.port")
	_ = config.GetString("log.level")
}

func NewConfigWithOptions

func NewConfigWithOptions(options ...Option) *Config

func (*Config) AllSettings added in v1.0.1

func (c *Config) AllSettings() map[string]any

func (*Config) AllowEmptyEnv

func (c *Config) AllowEmptyEnv(allowEmptyEnv bool)

func (*Config) AutomaticEnv

func (c *Config) AutomaticEnv()

func (*Config) Bind

func (c *Config) Bind(name string, data any)
Example
package main

import (
	"github.com/ace-zhaoy/gviper"
)

func main() {
	type LogConfig struct {
		Type  string `json:"type"`
		Level string `json:"level"`
	}

	type AppConfig struct {
		Name string `json:"name"`
	}

	config := gviper.NewConfig(".")

	var lc LogConfig
	var ac AppConfig

	config.Bind("log.toml", &lc)
	config.Bind("app", &ac)

	_ = config.Load()
	config.Watch()

	_ = lc.Level
	_ = ac.Name
}
Example (Register)
package main

import (
	"github.com/ace-zhaoy/gviper"
)

func main() {
	type LogConfig struct {
		Type  string `json:"type"`
		Level string `json:"level"`
	}

	type AppConfig struct {
		Name string `json:"name"`
	}

	config := gviper.NewConfig(".", "log.toml", "app")

	var lc LogConfig
	var ac AppConfig

	config.Bind("log", &lc)
	config.Bind("app", &ac)

	_ = config.Load()
	config.Watch()

	_ = lc.Level
	_ = ac.Name
}

func (*Config) BindAndListen added in v1.0.4

func (c *Config) BindAndListen(name string, data any, listener Listener)

func (*Config) BindWithTag

func (c *Config) BindWithTag(name string, data any, tagName string, decoderConfigOptions ...viper.DecoderConfigOption)
Example
package main

import (
	"github.com/ace-zhaoy/gviper"
	"github.com/mitchellh/mapstructure"
	"time"
)

func main() {
	type LogConfig struct {
		Type  string `yaml:"type"`
		Level string `yaml:"level"`
	}

	type AppConfig struct {
		Name string `yaml:"name"`
	}

	type DateConfig struct {
		Date time.Time `yaml:"date"`
	}

	config := gviper.NewConfig(".")

	var lc LogConfig
	var ac AppConfig
	var dc DateConfig

	config.BindWithTag("log.toml", &lc, "yaml")
	config.BindWithTag("app", &ac, "yaml")
	config.BindWithTag("date", &dc, "yaml", func(d *mapstructure.DecoderConfig) {
		d.DecodeHook = mapstructure.ComposeDecodeHookFunc(
			d.DecodeHook,
			mapstructure.StringToTimeDurationHookFunc(),
		)
	})

	_ = config.Load()
	config.Watch()

	_ = lc.Level
	_ = ac.Name
}

func (*Config) Default added in v1.0.2

func (c *Config) Default(key string, defaultValue any) any

func (*Config) DefaultBool added in v1.0.2

func (c *Config) DefaultBool(key string, defaultValue bool) bool

func (*Config) DefaultDuration added in v1.0.2

func (c *Config) DefaultDuration(key string, defaultValue time.Duration) time.Duration

func (*Config) DefaultFloat64 added in v1.0.2

func (c *Config) DefaultFloat64(key string, defaultValue float64) float64

func (*Config) DefaultInt added in v1.0.2

func (c *Config) DefaultInt(key string, defaultValue int) int

func (*Config) DefaultInt32 added in v1.0.2

func (c *Config) DefaultInt32(key string, defaultValue int32) int32

func (*Config) DefaultInt64 added in v1.0.2

func (c *Config) DefaultInt64(key string, defaultValue int64) int64

func (*Config) DefaultIntSlice added in v1.0.2

func (c *Config) DefaultIntSlice(key string, defaultValue []int) []int

func (*Config) DefaultSizeInBytes added in v1.0.2

func (c *Config) DefaultSizeInBytes(key string, defaultValue uint) uint

func (*Config) DefaultString added in v1.0.2

func (c *Config) DefaultString(key string, defaultValue string) string

func (*Config) DefaultStringMap added in v1.0.2

func (c *Config) DefaultStringMap(key string, defaultValue map[string]any) map[string]any

func (*Config) DefaultStringMapString added in v1.0.2

func (c *Config) DefaultStringMapString(key string, defaultValue map[string]string) map[string]string

func (*Config) DefaultStringMapStringSlice added in v1.0.2

func (c *Config) DefaultStringMapStringSlice(key string, defaultValue map[string][]string) map[string][]string

func (*Config) DefaultStringSlice added in v1.0.2

func (c *Config) DefaultStringSlice(key string, defaultValue []string) []string

func (*Config) DefaultTime added in v1.0.2

func (c *Config) DefaultTime(key string, defaultValue time.Time) time.Time

func (*Config) DefaultUint added in v1.0.2

func (c *Config) DefaultUint(key string, defaultValue uint) uint

func (*Config) DefaultUint32 added in v1.0.2

func (c *Config) DefaultUint32(key string, defaultValue uint32) uint32

func (*Config) DefaultUint64 added in v1.0.2

func (c *Config) DefaultUint64(key string, defaultValue uint64) uint64

func (*Config) Get

func (c *Config) Get(key string) any

func (*Config) GetBool

func (c *Config) GetBool(key string) bool

func (*Config) GetDuration

func (c *Config) GetDuration(key string) time.Duration

func (*Config) GetFloat64

func (c *Config) GetFloat64(key string) float64

func (*Config) GetInt

func (c *Config) GetInt(key string) int

func (*Config) GetInt32

func (c *Config) GetInt32(key string) int32

func (*Config) GetInt64

func (c *Config) GetInt64(key string) int64

func (*Config) GetIntSlice

func (c *Config) GetIntSlice(key string) []int

func (*Config) GetSizeInBytes

func (c *Config) GetSizeInBytes(key string) uint

func (*Config) GetString

func (c *Config) GetString(key string) string

func (*Config) GetStringMap

func (c *Config) GetStringMap(key string) map[string]any

func (*Config) GetStringMapString

func (c *Config) GetStringMapString(key string) map[string]string

func (*Config) GetStringMapStringSlice

func (c *Config) GetStringMapStringSlice(key string) map[string][]string

func (*Config) GetStringSlice

func (c *Config) GetStringSlice(key string) []string

func (*Config) GetTime

func (c *Config) GetTime(key string) time.Time

func (*Config) GetUint

func (c *Config) GetUint(key string) uint

func (*Config) GetUint32

func (c *Config) GetUint32(key string) uint32

func (*Config) GetUint64

func (c *Config) GetUint64(key string) uint64

func (*Config) Has

func (c *Config) Has(key string) bool

func (*Config) IsSet

func (c *Config) IsSet(key string) bool

func (*Config) Load

func (c *Config) Load() (err error)
Example
package main

import (
	"github.com/ace-zhaoy/gviper"
)

func main() {
	config := gviper.NewConfig(".", "app", "database.json", "log.toml")

	_ = config.Load()
}

func (*Config) OnChange

func (c *Config) OnChange(name string, listener Listener)

func (*Config) Register

func (c *Config) Register(names ...string)
Example
package main

import (
	"github.com/ace-zhaoy/gviper"
)

func main() {
	config := gviper.NewConfig(".")

	config.Register("app", "database.json", "log.toml")

	// 加载配置文件
	if err := config.Load(); err != nil {
		panic(err)
	}

	// 监听配置文件变化(非阻塞)
	config.Watch()

	_ = config.GetString("app.name")
	_ = config.GetInt("database.port")
	_ = config.GetString("log.level")
}

func (*Config) RegisterNotification

func (c *Config) RegisterNotification(notifications ...Notification)
Example
package main

import (
	"github.com/ace-zhaoy/gviper"
	"github.com/ace-zhaoy/gviper/notifications"
)

func main() {
	config := gviper.NewConfig(".", "app", "database.json", "log.toml")
	config.RegisterNotification(
		notifications.NewFeishuBotHook("https://open.feishu.cn/open-apis/bot/v2/hook/xxx"),
	)

	_ = config.Load()
	config.Watch()
}

func (*Config) Sub added in v1.0.1

func (c *Config) Sub(key string) *viper.Viper

func (*Config) Watch

func (c *Config) Watch()
Example
package main

import (
	"github.com/ace-zhaoy/gviper"
)

func main() {
	config := gviper.NewConfig(".", "app", "database.json", "log.toml")

	_ = config.Load()
	config.Watch()
}

type Listener

type Listener func(viper *viper.Viper) error

type Notification

type Notification interface {
	Notify(configName string, err error)
}

type Option

type Option func(*Config)

func WithAllowEmptyEnv

func WithAllowEmptyEnv(allowEmptyEnv bool) Option

func WithAutomaticEnv

func WithAutomaticEnv() Option

func WithConfigPath

func WithConfigPath(configPath string) Option

func WithDecoderConfigOptions added in v1.0.3

func WithDecoderConfigOptions(options ...viper.DecoderConfigOption) Option

func WithDefaultConfigType

func WithDefaultConfigType(configType string) Option

func WithNotification

func WithNotification(notifications ...Notification) Option

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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