# z1cnf **Repository Path**: z1gotool/z1cnf ## Basic Information - **Project Name**: z1cnf - **Description**: for config - **Primary Language**: Go - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-10-03 - **Last Updated**: 2026-07-09 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # z1cnf 轻量级 YAML 配置库,开箱即用。自动读取 `config/config.yaml`,支持点号分隔的路径访问、结构体生成及配置模板功能。 ## 特性 - 自动读取 `config/config.yaml` 配置文件 - 点号分隔路径访问(如 `db.host`、`db.dbs.2`) - 丰富的类型化获取函数(string、int、float64、bool、duration、slice、map 等) - 配置模板:未找到配置文件时根据模板自动生成并提醒修改 - 结构体生成:通过 `go:generate` 自动生成类型安全的配置结构体 ## 安装 ```bash go get gitee.com/z1gotool/z1cnf ``` ## 快速开始 ```go package main import ( "fmt" "gitee.com/z1gotool/z1cnf" ) func main() { // 直接读取 config/config.yaml host := z1cnf.GetString("db.host") port := z1cnf.GetInt("db.port") fmt.Println(host, port) // 获取全部配置 all := z1cnf.Get("") fmt.Println(all) // 使用类型安全结构体 fmt.Println(z1cnf.Struct.Db.Host) } ``` ## 配置模板用法 当配置文件不存在时,可根据模板自动生成: ```go package main import ( _ "embed" "gitee.com/z1gotool/z1cnf" ) //go:embed config/config_template.yaml var z1cnfContent []byte var _ = z1cnf.SetConfigTemplate(z1cnfContent) ``` 运行后若配置文件不存在,将自动生成并提示修改重启。 ## 结构体生成 通过 `go:generate` 自动生成类型安全的配置结构体: ```go //go:generate go run gitee.com/z1gotool/z1cnf/cnf2struct ``` 生成后可直接使用 `z1cnf.Struct` 访问配置字段,如 `z1cnf.Struct.Db.Host`。 ## API 参考 | 函数 | 说明 | |------|------| | `Get(key)` | 获取原始值,空字符串返回全部配置 | | `GetString(key)` | 获取 string 值 | | `GetInt(key)` | 获取 int 值(兼容 float64) | | `GetFloat64(key)` | 获取 float64 值(兼容 int) | | `GetBool(key)` | 获取 bool 值 | | `GetDuration(key)` | 获取 time.Duration(支持 string/int/float64) | | `GetSlice(key)` | 获取 `[]interface{}` | | `GetSliceString(key)` | 获取 `[]string` | | `GetSliceInt(key)` | 获取 `[]int`(兼容 float64) | | `GetSliceFloat64(key)` | 获取 `[]float64`(兼容 int) | | `GetSliceBool(key)` | 获取 `[]bool`(兼容 string) | | `GetStringMap(key)` | 获取 `map[string]interface{}` | | `GetStringMapString(key)` | 获取 `map[string]string` | | `GetStringMapInt(key)` | 获取 `map[string]int`(兼容 float64) | | `GetStringMapBool(key)` | 获取 `map[string]bool`(兼容 string) | | `GetStringMapFloat64(key)` | 获取 `map[string]float64`(兼容 int) | | `GetStringMapDuration(key)` | 获取 `map[string]time.Duration`(支持 string/int/float64) | | `GetSliceDuration(key)` | 获取 `[]time.Duration`(支持 string/int/float64) | | `Has(key)` | 检查 key 是否存在 | | `SetFilePath(path)` | 设置配置文件路径 | | `LoadConfigFile()` | 重新读取并解析配置文件 | | `Load2Struct(ptr)` | 将配置反序列化到结构体 | | `GenConfigTemplate()` | 生成配置模板文件 | | `SetConfigTemplate(content)` | 根据内容生成配置文件 | ## License Apache 2.0