configmanager

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 4 Imported by: 0

README

go-config-manager

Go Reference

Per-app configuration stored as JSON in the user config directory. Zero dependencies.


For Users

Install

go get github.com/mesopix/go-config-manager
import "github.com/mesopix/go-config-manager"

Usage

Create a default_config.json template file and embed it:

//go:embed default_config.json
var defaultConfigJSON []byte

c, err := configmanager.LoadAppConfig("myapp", defaultConfigJSON) // always returns a config
if err != nil { ... }

port, _ := c.Get("port")
c.Set("port", 9090)
if err := c.Save(); err != nil { ... }

The file lives at <user config dir>/myapp/config.json; on first run it is created from the embedded JSON template.

Note: JSON numbers come back as float64 from Get.

API Reference

Full API documentation is available on pkg.go.dev.


For Developers

Project Structure

.
├── config.go           # Core library: LoadAppConfig, Config, Get, Set, Save
├── config_test.go      # Tests
└── examples/
    └── demo/
        ├── default_config.json  # Embedded default config template
        └── main.go              # Runnable demo

Single package at module root, zero external dependencies.

Development Guide

Run tests and static analysis:

go test -v ./...
go vet ./...

Tests use t.TempDir() and override AppData / XDG_CONFIG_HOME / HOME via t.Setenv, so they never touch real user config.

Design Decisions

  • No auto-detection of executable name: Renaming the binary would silently create a new config file, losing previous settings. Test binaries would also use different config paths. Multiple binaries in the same project often share one config. The caller explicitly provides appName.
  • Re-read after first save: On first run, LoadAppConfig writes the embedded JSON defaults to disk then reads it back. This ensures numeric types are always float64 (matching subsequent runs), avoiding subtle type mismatches between first and later launches.
  • Atomic save: Save() writes to a temp file in the same directory, calls Sync() to flush to disk, then Renames over the target. A crash during save never leaves a half-written config.
  • Zero dependencies: Only stdlib (encoding/json, os, path/filepath). Keeps the dependency tree minimal for a utility library.

Release Process

  1. Ensure all tests pass: go test -v ./... && go vet ./...

  2. Commit all changes to main.

  3. Create and push a semantic version tag:

    git tag v0.x.y
    git push origin main --tags
    
  4. pkg.go.dev will automatically pick up the new version within minutes.

⚠️ Published tags are immutable — never delete or move them. Use a new version number for any change.

Documentation

Overview

包 configmanager 是一个基于 JSON 文件的轻量级配置存储库。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CheckResult added in v0.3.0

type CheckResult int

CheckResult 表示 data 相对于 schema 的校验状态。

const (
	Valid           CheckResult = iota // 严格符合 schema
	MissingDefaults                    // 仅缺少带默认值的非必填字段
	ExtraFields                        // 仅有 schema 未定义的多余字段
	MissingAndExtra                    // 既缺带默认值的字段,又有多余字段
	Invalid                            // 必填缺失或类型不匹配
)

type Config

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

Config 持有以磁盘 JSON 文件为后端的配置值。

func LoadAppConfig

func LoadAppConfig(appName string, defaultJSON []byte) (*Config, error)

LoadAppConfig 加载 appName 对应的配置。首次运行时从 defaultJSON 创建配置文件, 因此除非发生 I/O 或解析错误,否则总会返回一个配置对象。 defaultJSON 应为合法的 JSON 对象(如通过 //go:embed 嵌入的模板文件)。 数值会从磁盘读回,所以类型统一为 float64。

func (*Config) Get

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

Get 返回 key 下存储的值以及它是否存在。 JSON 数值会被反序列化为 float64。

func (*Config) Save

func (c *Config) Save() error

Save 以原子方式把当前值写回 JSON 文件。 先写入临时文件并同步到磁盘,再重命名覆盖目标文件, 这样即使中途崩溃也不会留下写了一半的配置。

func (*Config) Set

func (c *Config) Set(key string, value any)

Set 将 value 存储到 key 下。

type FieldDef added in v0.3.0

type FieldDef struct {
	Type     FieldType
	Required bool
	Default  any // nil 表示无默认值;仅当 Required 为 false 时有意义
}

FieldDef 描述一个配置键:期望类型、是否必填,以及可选的默认值(仅在非必填时生效)。

type FieldType added in v0.3.0

type FieldType int

FieldType 表示配置字段期望的 JSON 类型。

const (
	TypeString FieldType = iota // JSON 字符串
	TypeFloat                   // JSON 数值(float64)
	TypeBool                    // JSON 布尔值
	TypeArray                   // JSON 数组
	TypeObject                  // JSON 对象
)

type Schema added in v0.3.0

type Schema map[string]FieldDef

Schema 是以配置键名为索引的字段定义集合。 它有意独立于 Config,使调用方自行掌控 schema 与校验生命周期。

func (Schema) Check added in v0.3.0

func (s Schema) Check(data map[string]any) CheckResult

Check 只读检查 data 相对于 schema 的状态,不修改 data。

func (Schema) Normalize added in v0.3.0

func (s Schema) Normalize(data map[string]any) (map[string]any, error)

Normalize 返回 data 的规范化副本:补全缺失的默认值,删除多余字段。 原 data 不会被修改。仅当 Check 结果为 MissingDefaults / ExtraFields / MissingAndExtra 时才能成功转换;其他状态返回 error。

Directories

Path Synopsis
examples
demo command
命令 demo 演示其他项目如何使用 configmanager。
命令 demo 演示其他项目如何使用 configmanager。

Jump to

Keyboard shortcuts

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