confx

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2026 License: MIT Imports: 7 Imported by: 0

README

Confx: Go Production-Ready Configuration

Go Report Card

confx 是一个为 Go 语言打造的生产级配置管理库。它集成了 Viper 的强大加载能力和 Validator 的精准校验,并针对微服务云原生高频 API 场景进行了深度优化。

它的核心设计哲学是:默认即最佳(Convention over Configuration)极致性能(Performance at Scale)

核心特性 (Features)

  • 泛型支持 (Generics): 使用 Load[T]() 直接返回强类型结构体,告别繁琐的类型断言和变量声明。
  • 混合验证模式 (Hybrid Validation):
  • 反射模式: 使用 Tag 开发,简单快捷。
  • 极速模式: 实现 Validatable 接口,绕过反射,专为热点路径设计。
  • 智能默认值: 支持 default 标签设置默认值。
  • 严格解码: 防止配置文件中出现未定义的字段(避免拼写错误被忽略)。

安装 (Installation)

go get github.com/atomreforge/confx

快速开始 (Quick Start)

1. 定义配置结构体
package main

import (
    "fmt"
    "github.com/atomreforge/confx"
)

type DBConfig struct {
    // 支持 mapstructure 映射,validate 校验,default 默认值
    Host string `mapstructure:"host" validate:"required"`
    Port int    `mapstructure:"port" validate:"min=1024" default:"3306"`
}

type Config struct {
    AppName string   `mapstructure:"app_name" default:"MyApp"`
    Debug   bool     `mapstructure:"debug"`
    DB      DBConfig `mapstructure:"db"`
}

func main() {
    // 一行代码加载 + 解析 + 验证 + 默认值
    // 默认搜索当前目录下的 config.yaml
    cfg := confx.MustLoad[Config]("myapp")

    fmt.Printf("App: %s, DB Port: %d\n", cfg.AppName, cfg.DB.Port)
}
2. 配置文件 (config.yaml)
app_name: "SuperService"
debug: true
db:
  host: "127.0.0.1"
  # port 使用默认值 3306
3. 运行
go run main.go

高级特性

1. 混合验证模式 (Performance)

对于 QPS 极高的场景,反射带来的开销虽然很小,但依然存在。confx 支持通过实现接口来绕过反射

type FastRequest struct {
    APIKey string
}

// 实现 Validatable 接口
// Confx 会自动检测并直接调用此方法,耗时仅需 ~4.5ns
func (r *FastRequest) Validate() error {
    if len(r.APIKey) != 32 {
        return fmt.Errorf("invalid api_key")
    }
    return nil
}

配置选项 (Options)

加载配置时支持以下 Option:

Option 说明 默认值
WithSearchPaths(paths...) 配置文件搜索路径 ../config
WithFileName(name) 配置文件名 config
WithFileType(type) 文件类型 (yaml, json, toml...) yaml

性能基准测试 (Benchmarks)

基于 Intel i9-13900HX 的测试数据:

验证模式 耗时 (ns/op) 内存分配 (B/op) 性能提升
Reflect (Tag) 152.3 ns 24 B 基准
Interface (Fast) 4.5 ns 0 B ~33x
Direct Call 0.45 ns 0 B 理论极限

建议: 配置加载场景使用 Tag 模式(开发效率高);在极度敏感的热点代码中使用 Interface/原生 模式; 。

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Load

func Load[T any](appName string, opts ...Option) (*T, error)

Load loads and validates configuration

func MustLoad

func MustLoad[T any](appName string, opts ...Option) *T

Types

type CustomValidator

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

func NewCustomValidator

func NewCustomValidator() *CustomValidator

func (*CustomValidator) Validate

func (v *CustomValidator) Validate(i any) error

type Option

type Option func(*options)

func WithFileName

func WithFileName(n string) Option

func WithFileType

func WithFileType(t string) Option

WithFileType yaml/json/toml

func WithSearchPaths

func WithSearchPaths(paths ...string) Option

WithSearchPaths

type Validatable

type Validatable interface {
	Validate() error
}

type ValidationError

type ValidationError struct {
	Errors map[string]string
}

func (*ValidationError) Error

func (e *ValidationError) Error() string

Jump to

Keyboard shortcuts

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