easyconf

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2025 License: MIT Imports: 10 Imported by: 3

README

简介

简单的Go应用程序配置工具,用于生成和读取 env 配置文件的环境变量。

可以很方便地定义 配置名默认值注释标题注释说明(多行)。

通过简单的方法读取和修改配置值。

优先级:命令行同名参数值 > 环境变量值 > 配置文件配置值

新建配置

导入 easyconf 工具包:

import (
	"github.com/iotames/easyconf"
)

可初始化1个或多个配置文件,优先级从左到右。默认: .env, default.env

// 生成 .env, default.env 两份配置文件。
cf := easyconf.NewConf()

// 生成一份 myconf.env 自定义配置文件。
cf = easyconf.NewConf("myconf.env")

// 生成多份配置文件
cf = easyconf.NewConf(".env", "common.env", "default.env")

使用 Parse(fale) 方法读取文件中的配置值。若文件不存在,则创建。

var DbHost string
var DbPort int
cf := easyconf.NewConf()
cf.StringVar(&DbHost, "DB_HOST", "127.0.0.1", "数据库主机地址")
cf.IntVar(&DbPort, "DB_PORT", 3306, "数据库地址端口号")
cf.Parse(false) // 默认创建 .env, default.env 两份文件。

更新配置

使用 UpdateFile() 方法更新配置。需要指定配置文件路径,留空则默认更新第一个。

cf := easyconf.NewConf(".env")
var DbHost string
cf.StringVar(&DbHost, "DB_HOST", "127.0.0.1", "数据库主机地址")
cf.Parse(false)

DbHost = "192.168.1.6"

// 可指定一个更新的配置文件。留空则默认更新第一个。
err := cf.UpdateFile("")
if err != nil {
	panic(err)
}

完整示例

package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/iotames/easyconf"
)

// 可修改 envfile 文件中配置项的值,验证值是否更新
const DEFAULT_ENV_FILE = ".env"

const DEFAULT_DB_HOST = "127.0.0.1"
const DEFAULT_DB_PORT = 3306

var envfile string

var cf *easyconf.Conf

var DbHost string
var DbPort int
var DbEnable bool
var AllowIPs []string
var AgeRange []int

func main() {
	fmt.Printf("-------可修改envfile(%s)文件中配置项的默认值,验证修改值是否更新-----\n", getEnvFile())
	fmt.Printf("-----DbHost(%s)--DbPort(%d)--Dbnable(%t)--\n", DbHost, DbPort, DbEnable)
	fmt.Printf("-----AllowIPs(%+v)--AgeRange(%v)--\n", AllowIPs, AgeRange)
	if DbHost == DEFAULT_DB_HOST {
		DbHost = "192.168.1.19"
		DbPort = 3308
		err := cf.UpdateFile(getEnvFile())
		if err != nil {
			panic(err)
		}
		fmt.Printf("SUCCESS: Update Env File:%s\n", getEnvFile())
	}
}

func init() {
	flag.StringVar(&envfile, "envfile", "", "配置文件路径")
	flag.Parse()
	cf = easyconf.NewConf(getEnvFile())
	cf.StringVar(&DbHost, "DB_HOST", DEFAULT_DB_HOST, "数据库主机地址")
	cf.IntVar(&DbPort, "DB_PORT", DEFAULT_DB_PORT, "数据库地址端口号")
	cf.BoolVar(&DbEnable, "DB_ENABLE", false, "是否启用数据库")
	cf.StringListVar(&AllowIPs, "ALLOW_IP_LIST", []string{"192.168.1.6", "192.168.2.8"}, "允许访问的IP列表,每个IP用逗号(,)隔开。")
	cf.IntListVar(&AgeRange, "AGE_RANGE", []int{3, 6}, "年龄范围", "填写2个正整数,中间用逗号,隔开")
	cf.Parse(false)
}

func getEnvFile() string {
	efile := envfile
	if efile == "" {
		efile = os.Getenv("ENV_FILE")
	}
	if efile == "" {
		efile = DEFAULT_ENV_FILE
	}
	return efile
}


Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetConfStrByLine

func GetConfStrByLine(line string) (itemk, itemv string)

GetConfStrByLine 从单行字符串中提取配置项的键值对字符串

Types

type Conf

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

func NewConf

func NewConf(files ...string) *Conf

NewConf 定义配置文件。留空默认为: .env, default.env 配置优先级:命令行参数 > 系统环境变量 > 配置文件列表(按顺序,优先级依次降低) 配置文件列表:首个文件优先级最高。前面文件的配置值,会覆盖后面文件的配置值。

func (*Conf) AddComment

func (cf *Conf) AddComment(title string, comment ...string)

func (*Conf) BoolVar

func (cf *Conf) BoolVar(pval *bool, name string, defval bool, title string, usage ...string)

func (Conf) DefaultString

func (cf Conf) DefaultString() string

DefaultString 默认配置的文件内容

func (*Conf) Float64Var

func (cf *Conf) Float64Var(pval *float64, name string, defval float64, title string, usage ...string)

func (*Conf) IntListVar

func (cf *Conf) IntListVar(pval *[]int, name string, defval []int, title string, usage ...string)

func (*Conf) IntVar

func (cf *Conf) IntVar(pval *int, name string, defval int, title string, usage ...string)

func (*Conf) Parse

func (cf *Conf) Parse(flagParse bool) error

Parse 从配置文件和系统环境变量解析配置。

如flagParse为true,还会从命令行参数解析配置。但会和原生的flag.Parse()冲突。 其他地方还有调用flag.Parse()的代码,应删除,由本方法统一调用。

配置优先级:命令行参数 > 系统环境变量 > 配置文件列表(按顺序,优先级依次降低)

func (*Conf) SetValuesByCmdArgs added in v1.2.0

func (cf *Conf) SetValuesByCmdArgs() []error

SetValuesByCmdArgs 从命令行参数获取配置。优先级高 允许设置值为空字符串。

func (*Conf) SetValuesByEnv added in v1.2.0

func (cf *Conf) SetValuesByEnv() error

SetValuesByEnv 从操作系统的环境变量获取配置。优先级中 配置值为空字符串会被忽略

func (*Conf) SetValuesByEnvFile added in v1.2.0

func (cf *Conf) SetValuesByEnvFile(envfile string)

SetValuesByEnvFile 从env配置文件更新配置项。优先级低。 配置值为空字符串会被忽略

func (Conf) String

func (cf Conf) String() string

func (*Conf) StringListVar

func (cf *Conf) StringListVar(pval *[]string, name string, defval []string, title string, usage ...string)

func (*Conf) StringVar

func (cf *Conf) StringVar(pval *string, name string, defval, title string, usage ...string)

func (*Conf) UpdateFile

func (cf *Conf) UpdateFile(fpath string) error

type ConfItem

type ConfItem struct {
	Name         string // 配置项键名。键名为空字符串,则该项的值可能为注释。
	Title        string
	ValueStr     string // 配置项的字符串原始值。对于只有字符串类型的环境变量很有用。
	Value        any    // 配置项的值,类型为指针,引用传递。
	DefaultValue any    // 配置项的默认值,值传递。
	Usage        []string
}

ConfItem 配置项信息。 包含配置名,标题,配置值,默认值,使用说明。

func (ConfItem) DefaultString

func (item ConfItem) DefaultString() string

func (ConfItem) GetDefaultValue

func (item ConfItem) GetDefaultValue() string

func (ConfItem) GetValue

func (item ConfItem) GetValue() string

func (ConfItem) String

func (item ConfItem) String() string

type JsonConf added in v1.1.3

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

JsonConf 以 JSON 文件格式保存和读取配置

func NewJsonConf added in v1.1.3

func NewJsonConf(dirPath string) *JsonConf

NewJsonConf 创建 JsonConf 实例,dirPath 为配置文件存放目录

func (JsonConf) Read added in v1.1.3

func (c JsonConf) Read(v any, filename string) error

Read 从 dirPath/filename 文件中读取配置到 v filename 不包含目录路径。应该包含 .json 后缀,如 config.json。

func (JsonConf) Save added in v1.1.3

func (c JsonConf) Save(v any, filename string) error

Save 将配置 v 保存到 dirPath/filename 文件中 filename 不包含目录路径。应该包含 .json 后缀,如 config.json。

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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