config

package
v1.3.6 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2026 License: MIT Imports: 5 Imported by: 2

README

Config

config 包定义了统一配置能力的核心契约,目标是让业务只依赖 go-micro/config,再由具体后端实现包提供存储与监听能力。

当前主线口径:统一的是契约、读取语义与控制面边界,不是把多个后端实现同时打进一个运行时产物。当前交付主线中,IDC 使用 go-consul/configK8s + Istio 使用 go-k8s/config

设计目标

  • 统一配置模型,避免不同后端字段语义漂移
  • 统一存储与监听接口,降低后端切换成本
  • 统一选项与错误语义,减少重复治理逻辑
  • 支持运行时按 Key 读取配置
  • 统一加密语义:一份配置要加密就整份加密,读取时按 Raw.Encrypted 决定是否先解密再解析

加密处理规则

配置加密遵循以下原则:

  1. 加密粒度:整份配置,不做字段级加密
  2. 标识方式:通过 Raw.Encrypted 字段标识
  3. 读取规则
    • Raw.Encrypted=false:直接 JSON 解析 Content
    • Raw.Encrypted=true:必须先通过 PayloadDecodeFunc 解密整份 Content,再解析为目标结构
  4. 写入规则
    • 普通配置:直接写入明文内容,设置 Encrypted=false
    • 敏感配置:先加密整份内容,再写入,设置 Encrypted=true

示例

// 读取加密配置
raw, err := store.Get(ctx, key)
if err != nil {
    return err
}

if raw.Encrypted {
    // 必须先解密整份内容
    decrypted, err := decrypt(raw.Content, appSecret)
    if err != nil {
        return err
    }
    // 再解析为目标结构
    err = json.Unmarshal(decrypted, &config)
} else {
    // 明文配置直接解析
    err = json.Unmarshal(raw.Content, &config)
}

目录说明

  • model.go:配置主键、配置内容、版本元数据、监听事件模型
  • store.go:统一存储接口
  • watch.go:统一监听接口
  • option.go:函数式配置选项与可插拔能力(Codec/Encryptor)
  • loader.go:统一配置加载入口,负责按 local / remote 方式加载基础配置,并支持从 Store 读取配置对象
  • loader_qa.md:记录 loader 命名与参数设计上的关键取舍,避免后续语义漂移
  • error.go:统一错误定义
  • bootstrap.go:启动配置接口
  • logger.go:日志配置接口
  • telemetry.go:遥测配置接口

命名约定

  • BootstrapConfig 是业务服务自己的启动配置模型,表示程序启动时只初始化一次的基础引导配置,这类配置通常不参与热更新
  • go-micro/config 不定义具体业务侧的 BootstrapConfig 结构,而是提供通用加载能力,因此这里使用 loader 命名
  • LoaderParams + LoadConfig 用于描述"如何从 local / remote 加载一份基础配置"
  • StoreParams + LoadStoreConfig 用于描述"如何从统一配置存储中读取并解析一份配置"
  • Raw.Encrypted 表示"当前整份配置内容是否为密文",不支持字段级加密
  • 这样区分后,业务侧可以继续保留 BootstrapConfig 语义,基础库侧则专注于加载过程,避免把"配置模型"和"加载动作"混在一起
  • 关于为什么当前不把 LoadConfig 的参数进一步收敛成统一接口,可参考 loader_qa.md

使用方式

1) 实现 Store + Watcher

由各后端实现包完成。

当前主线交付中:

  • IDC:go-consul/config
  • K8s + Istiogo-k8s/config
2) 业务侧依赖抽象

业务代码依赖 Store/Watcher 接口,不直接依赖具体后端实现。

3) 配置分层建议
  • 启动层:本地 BootstrapConfig
  • 动态层:后端 watch 热更新
  • 场景层:按 Key 查询
4) 加密读取规则
  • Raw.Encrypted=false:直接解析配置内容
  • Raw.Encrypted=true:先解密整份配置内容,再解析目标结构
  • 如果只有部分敏感信息需要保护,应拆成独立配置项,而不是在同一份 JSON 中做字段级加密

最小示例

package main

import (
	"context"

	microcfg "github.com/fireflycore/go-micro/config"
)

func load(ctx context.Context, store microcfg.Store) (*microcfg.Raw, error) {
	key := microcfg.Key{
		TenantId: "t1",
		Env:      "prod",
		AppId:    "order-service",
		Group:    "db",
		Name:     "primary",
	}
	return store.Get(ctx, key)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrLocalLoaderIsNil 表示本地加载函数为空。
	ErrLocalLoaderIsNil = errors.New("config local loader is nil")
	// ErrRemoteLoaderIsNil 表示远程加载函数为空。
	ErrRemoteLoaderIsNil = errors.New("config remote loader is nil")
	// ErrPayloadDecoderIsNil 表示配置内容解码函数为空。
	ErrPayloadDecoderIsNil = errors.New("config payload decoder is nil")
	// ErrStoreIsNil 表示存储实现为空。
	ErrStoreIsNil = errors.New("config store is nil")
	// ErrWatcherIsNil 表示监听实现为空。
	ErrWatcherIsNil = errors.New("config watcher is nil")
	// ErrCodecIsNil 表示编解码实现为空。
	ErrCodecIsNil = errors.New("config codec is nil")
	// ErrEncryptorIsNil 表示加解密实现为空。
	ErrEncryptorIsNil = errors.New("config encryptor is nil")
	// ErrInvalidKey 表示配置键不合法。
	ErrInvalidKey = errors.New("invalid config key")
	// ErrInvalidRaw 表示配置内容不合法。
	ErrInvalidRaw = errors.New("invalid config raw")
	// ErrResourceNotFound 表示配置资源不存在。
	ErrResourceNotFound = errors.New("config resource not found")
	// ErrVersionConflict 表示写入版本冲突。
	ErrVersionConflict = errors.New("config version conflict")
	// ErrUnsupportedLoadMode 表示配置加载模式不支持。
	ErrUnsupportedLoadMode = errors.New("unsupported config load mode")
)

Functions

func LoadConfig added in v1.3.0

func LoadConfig[T any](params LoaderParams, localLoad LocalLoaderFunc, remoteLoad RemoteLoaderFunc, payloadDecode PayloadDecodeFunc) (T, error)

LoadConfig 按 local / remote 规则加载并解析后端配置。

func LoadStoreConfig added in v1.3.0

func LoadStoreConfig[T any](ctx context.Context, store Store, params StoreParams, payloadDecode PayloadDecodeFunc) (T, error)

LoadStoreConfig 从 Store 读取当前配置并解析为目标类型 T。 加密处理规则: - 当 Raw.Encrypted=false 时,直接 JSON 解析 Content - 当 Raw.Encrypted=true 时,必须先通过 payloadDecode 解密整份 Content,再解析为目标结构 - 不支持字段级加密,一份配置要加密就整份加密

Types

type BootstrapConfig added in v1.3.3

type BootstrapConfig interface {
	GetAppId() string
	GetAppSecret() string
	GetAppName() string
	GetAppVersion() string
	GetServiceEndpoint() string
	GetServiceAuthToken() string
	GetServiceNamespace() string
	GetServiceInstanceId() string

	GetSystemName() string
	GetSystemType() uint32
	GetSystemVersion() string

	GetGatewayEndpoint() string
	GetGatewayAuthToken() string

	GetServerPort() uint
	GetManagementPort() uint

	LoggerConfig
	TelemetryConfig
}

type Codec

type Codec interface {
	// Marshal 把结构化对象编码为字节。
	Marshal(v any) ([]byte, error)
	// Unmarshal 把字节解码到目标对象。
	Unmarshal(data []byte, dst any) error
}

Codec 定义配置内容序列化与反序列化能力。

type Encryptor

type Encryptor interface {
	// Encrypt 使用给定密钥加密数据。
	Encrypt(data []byte, key []byte) ([]byte, error)
	// Decrypt 使用给定密钥解密数据。
	Decrypt(data []byte, key []byte) ([]byte, error)
}

Encryptor 定义配置内容加解密能力。

type EventType

type EventType int

EventType 表示配置变更事件类型。

const (
	// EventPut 表示新增或更新事件。
	EventPut EventType = iota
	// EventDelete 表示删除事件。
	EventDelete
)

type Key

type Key struct {
	// TenantId 表示租户标识,用于多租户隔离。
	TenantId string `json:"tenant_id"`
	// AppId 表示应用标识。
	AppId string `json:"app_id"`
	// Env 表示环境,如 dev/staging/prod。
	Env string `json:"env"`

	// Group 表示配置分组。
	Group string `json:"group"`
	// Name 表示具体配置名。
	Name string `json:"name"`
}

Key 描述一条配置在存储中的业务主键。

type LoaderParams added in v1.3.0

type LoaderParams struct {
	// Mode 指定加载模式:local / remote。
	Mode string
	// AppId 远程模式下用于定位配置所属应用。
	AppId string
	// AppSecret 远程模式下用于解密整份配置内容(如果是密文)。
	AppSecret []byte
	// Group 配置分组(如 database)。
	Group string
	// Key 配置名(如 consul / etcd / k8s)。
	Key string
	// FileName 本地模式下使用的文件名(如 consul.json)。
	FileName string
}

LoaderParams 描述加载后端配置对象所需参数。 该结构把 local / remote 两条加载链路的输入参数统一起来。

type LocalLoaderFunc added in v1.3.0

type LocalLoaderFunc func(fileName string, target any) error

LocalLoaderFunc 定义本地配置加载函数签名。 典型实现是按 fileName 读取配置文件并反序列化到 target。

type LoggerConfig added in v1.3.3

type LoggerConfig interface {
	GetLoggerConsole() bool
	GetLoggerRemote() bool
}

type Option

type Option func(*Options)

Option 表示函数式配置项。

func WithCodec

func WithCodec(codec Codec) Option

WithCodec 注入自定义编解码实现。

func WithEncryptor

func WithEncryptor(encryptor Encryptor) Option

WithEncryptor 注入自定义加解密实现。

func WithNamespace

func WithNamespace(namespace string) Option

WithNamespace 设置配置命名空间。

func WithRetry

func WithRetry(retry uint32) Option

WithRetry 设置失败重试次数。

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout 设置单次请求超时时间。

func WithWatchBuffer

func WithWatchBuffer(size int) Option

WithWatchBuffer 设置监听事件缓冲区大小。

type Options

type Options struct {
	// Namespace 用于区分配置键空间。
	Namespace string
	// Timeout 用于单次请求超时控制。
	Timeout time.Duration
	// Retry 用于失败重试次数控制。
	Retry uint32
	// WatchBuffer 用于监听事件通道缓冲区大小。
	WatchBuffer int
	// Codec 为可选编解码器。
	Codec Codec
	// Encryptor 为可选加解密器。
	Encryptor Encryptor
}

Options 定义 config 组件的通用运行参数。

func NewOptions

func NewOptions(opts ...Option) *Options

NewOptions 生成带默认值的 Options,并按顺序应用外部参数。

type PayloadDecodeFunc added in v1.3.0

type PayloadDecodeFunc func(content string, secret []byte, target any) error

PayloadDecodeFunc 定义配置内容解码函数签名。 用于处理整份配置为密文的场景:先解密完整内容,再反序列化到 target。

type Raw added in v1.3.3

type Raw struct {
	// Meta 记录扩展元信息。
	Meta map[string]string `json:"meta"`
	// Version 表示配置版本号。
	Version string `json:"version"`
	// Content 是当前整份配置的原始内容。
	Content []byte `json:"content"`
	// Encrypted 标识当前整份 Content 是否已加密。
	// 当值为 true 时,读取方必须先解密整份内容,再做反序列化。
	Encrypted bool `json:"encrypted"`
	// CreatedAt 表示创建时间。
	CreatedAt time.Time `json:"created_at"`
	// UpdatedAt 表示最近更新时间。
	UpdatedAt time.Time `json:"updated_at"`
	// UpdatedBy 表示最近更新人。
	UpdatedBy string `json:"updated_by"`
}

Raw 表示一条可发布、可读取的配置内容。

type RemoteLoaderFunc added in v1.3.0

type RemoteLoaderFunc func(appId, group, key string) (string, error)

RemoteLoaderFunc 定义远程配置读取函数签名。 典型实现是从配置中心按 appId + group + key 获取配置文本。

type Store

type Store interface {
	// Get 按配置键读取当前生效配置。
	// 读取到的 Raw.Encrypted 标识整份配置是否为密文。
	// 当 Encrypted=true 时,调用方需要先解密整份 Content,再解析目标结构。
	Get(ctx context.Context, key Key) (*Raw, error)

	// Put 写入当前生效配置。
	// Raw.Encrypted 标识整份配置是否为密文。
	// 一份配置要加密就整份加密,不做字段级加密。
	Put(ctx context.Context, key Key, raw *Raw) error

	// Delete 删除当前配置。
	Delete(ctx context.Context, key Key) error
}

Store 定义统一配置存储抽象,供 consul/k8s 实现对齐。 配置变更监听能力由独立的 Watcher 接口承载,不并入 Store。

type StoreParams added in v1.3.0

type StoreParams struct {
	// Key 是优先使用的业务键。
	Key Key
	// AppId 用于回填 Key.AppId。
	AppId string
	// Env 用于回填 Key.Env。
	Env string
	// Group 用于回填 Key.Group。
	Group string
	// Name 用于回填 Key.Name。
	Name string
	// AppSecret 当读取到密文配置项时用于解码。
	AppSecret []byte
}

StoreParams 描述从 Store 读取一条配置并解析所需参数。 当 Key 某些字段为空时,会用 AppId / Env / Group / Name 回填。

type TelemetryConfig added in v1.3.3

type TelemetryConfig interface {
	GetOtelEndpoint() string
	GetOtelInsecure() bool

	GetOtelTraces() bool
	GetOtelMetrics() bool
	GetOtelLogs() bool
}

type WatchEvent

type WatchEvent struct {
	// Type 表示事件类型。
	Type EventType `json:"type"`
	// Key 表示事件对应的配置键。
	Key Key `json:"key"`
	// Raw 表示事件携带的配置内容。
	Raw *Raw `json:"raw"`
}

WatchEvent 表示 watch 通知事件。

type Watcher

type Watcher interface {
	// Watch 监听指定配置键的变更事件。
	Watch(ctx context.Context, key Key) (<-chan WatchEvent, error)
	// Unwatch 取消指定配置键的监听。
	Unwatch(key Key)
}

Watcher 定义统一配置监听抽象。

Jump to

Keyboard shortcuts

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