config

package
v2.7.0 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	DatabaseConfig  = new(Database)
	DatabasesConfig = make(map[string]*Database)
)
View Source
var ApplicationConfig = new(Application)
View Source
var CacheConfig = new(Cache)

CacheConfig cache配置

View Source
var (
	ExtendConfig interface{}
)
View Source
var GenConfig = new(Gen)
View Source
var JwtConfig = new(Jwt)
View Source
var LoggerConfig = new(Logger)
View Source
var QueueConfig = new(Queue)
View Source
var SslConfig = new(Ssl)

Functions

func RegisterExtend added in v2.5.0

func RegisterExtend[T any](key string) func() *T

RegisterExtend claims one section of the extend: config tree, keyed by key, and returns a function that always returns that section's most recently loaded value as a *T - on every load and every reload, independently of every other registered key, so the host and any number of applications can each keep their own configuration without one overwriting another's.

The returned function is the only thing a caller gets back; there is no target to unmarshal into, because there is nothing to synchronize. Every reload allocates a fresh *T from that reload's JSON and atomically replaces the one the accessor returns - it never writes through a pointer a caller might already be holding. A caller that reads the accessor once at startup and one that reads it from every request both get a complete, self-consistent value either way; neither needs a lock of its own, and T does not need to implement json.Unmarshaler to make that true. The accessor never returns nil, even before the first load completes: T's zero value is published immediately, so a caller does not need a nil check it would otherwise forget on the one code path that runs before Setup does its first Scan.

Call it only from init(), before Setup runs - the same convention as SetAppRouters and migration.ForApp. Registering the same key twice is a programming error (two callers would silently take turns owning one section, and whichever ran its init() last would win with no indication that the other's configuration was ever read) and panics immediately rather than letting it happen quietly.

func Setup

func Setup(s source.Source,
	fs ...func())

Setup 载入配置文件

Types

type Application

type Application struct {
	ReadTimeout   int
	WriterTimeout int
	Host          string
	Port          int64
	Name          string
	Mode          string
	DemoMsg       string
	EnableDP      bool
	// 租户模式:1:单租户 2:多租户
	TenantMode int `yaml:"tenantMode"`
}

type Cache

type Cache struct {
	Redis  *RedisOptions
	Memory interface{}
}

Cache selects the cache backend.

Leaving every field unset is a valid configuration and yields the in-memory cache, so a single instance runs with nothing beside it. Redis is opt-in and only for deployments that run more than one instance.

func (Cache) Open

func (e Cache) Open() (storage.Cache, error)

Open builds the configured cache. Order: redis > memory.

A redis section that cannot be reached is an error rather than a fallback: falling back would hand an operator who asked for a shared cache one that is not shared, and the symptom would only appear later, under load.

func (Cache) Setup deprecated

func (e Cache) Setup() (storage.AdapterCache, error)

Setup builds the cache adapter. Order: redis > memory.

Deprecated: use Open, which returns the current contract. This returns the older AdapterCache so that existing call sites keep working; storage.Cache can report a miss and takes a context, neither of which survives the bridge.

type Config

type Config struct {
	Application *Application          `yaml:"application"`
	Ssl         *Ssl                  `yaml:"ssl"`
	Logger      *Logger               `yaml:"logger"`
	Jwt         *Jwt                  `yaml:"jwt"`
	Database    *Database             `yaml:"database"`
	Databases   *map[string]*Database `yaml:"databases"`
	Gen         *Gen                  `yaml:"gen"`
	Cache       *Cache                `yaml:"cache"`
	Queue       *Queue                `yaml:"queue"`
	Extend      interface{}           `yaml:"extend"`
}

Config 配置集合

func GetConfig

func GetConfig() *Config

GetConfig 获取配置对象 返回当前加载的框架配置,如果未初始化则返回 nil

type DBResolverConfig

type DBResolverConfig struct {
	Sources  []string
	Replicas []string
	Policy   string
	Tables   []string
}

type Database

type Database struct {
	Driver          string
	Source          string
	ConnMaxIdleTime int
	ConnMaxLifeTime int
	MaxIdleConns    int
	MaxOpenConns    int
	Registers       []DBResolverConfig
}

type Gen

type Gen struct {
	DBName    string
	FrontPath string
}

type Jwt

type Jwt struct {
	Secret string
	// Timeout token 有效期,单位:秒
	Timeout int64
	// MaxRefresh 续期上限,单位:秒。
	//
	// 自 token 首次签发起计算,超过该时长后不再允许续期,必须重新登录。
	// 一个 token 的最长存活时间为 Timeout + MaxRefresh。
	//
	// 为 0 时由使用方决定默认值,本结构不做兜底。
	MaxRefresh int64
}

type Logger

type Logger struct {
	Type         string          `yaml:"type"`
	Adapter      string          `yaml:"adapter"`
	Path         string          `yaml:"path"`
	Level        string          `yaml:"level"`
	Stdout       string          `yaml:"stdout"`
	Encoder      string          `yaml:"encoder"`
	EnableCaller bool            `yaml:"enableCaller"`
	EnabledDB    bool            `yaml:"enableddb"`
	Cap          uint            `yaml:"cap"`
	Rotation     *RotationConfig `yaml:"rotation"`
}

func (Logger) Setup

func (e Logger) Setup()

Setup 设置logger(使用新的 logger 架构)

type Queue

type Queue struct {
	Redis  *RedisQueue
	Memory *QueueMemory
}

Queue selects the queue backend, on the same terms as Cache: memory unless a redis section says otherwise.

func (Queue) Empty

func (e Queue) Empty() bool

Empty 空设置

func (Queue) Open

func (e Queue) Open() (storage.Queue, error)

Open builds the configured queue. Order: redis > memory.

As with Cache.Open, an unreachable redis section is an error rather than a fallback to a queue that other instances cannot see.

func (Queue) Setup deprecated

func (e Queue) Setup() (storage.AdapterQueue, error)

Setup builds the queue adapter. Order: redis > memory.

Deprecated: use Open, which returns the current contract.

Note that the two branches do not behave identically, because the memory one stays on the older implementation: there, Register starts consuming on its own and retries a failed message three times, while the bridged Redis queue only consumes once Run is called. A call site that registers without running works on memory and silently consumes nothing on Redis.

type QueueMemory

type QueueMemory struct {
	PoolSize uint
}

type RedisOptions

type RedisOptions struct {
	URL        string `yaml:"url" json:"url"`
	Network    string `yaml:"network" json:"network"`
	Addr       string `yaml:"addr" json:"addr"`
	Username   string `yaml:"username" json:"username"`
	Password   string `yaml:"password" json:"password"`
	DB         int    `yaml:"db" json:"db"`
	PoolSize   int    `yaml:"pool_size" json:"pool_size"`
	MaxRetries int    `yaml:"max_retries" json:"max_retries"`
	Tls        *Tls   `yaml:"tls" json:"tls"`
}

RedisOptions describes how to reach a Redis server.

Set URL, which understands redis:// and rediss:// and is what a managed provider hands out, or fill in the individual fields. URL wins when both are present.

The json names are what the configuration file is keyed on, and they match the ones this repository used before Redis support was removed, so an older settings file still applies.

func (RedisOptions) Client

func (e RedisOptions) Client(ctx context.Context) (*goredis.Client, error)

Client connects and verifies the server answers, so that a wrong address fails the boot rather than the first request that needs the cache.

The returned client is shared with every other caller naming the same destination, and is not closed by this package.

func (RedisOptions) GetRedisOptions

func (e RedisOptions) GetRedisOptions() (*goredis.Options, error)

GetRedisOptions converts the configuration into client options.

type RedisQueue

type RedisQueue struct {
	RedisOptions `yaml:",inline"`

	Group       string `yaml:"group" json:"group"`
	KeyPrefix   string `yaml:"key_prefix" json:"key_prefix"`
	MaxAttempts int    `yaml:"max_attempts" json:"max_attempts"`

	// In seconds, because a settings file cannot express a time.Duration.
	ClaimMinIdleSeconds int `yaml:"claim_min_idle_seconds" json:"claim_min_idle_seconds"`
}

RedisQueue adds the consumer-group settings to a Redis connection.

The json names are what a settings file is keyed on. For what each setting means and what a zero value falls back to, see redisstore.QueueOptions; options absent here can only be set in code.

type RotationConfig

type RotationConfig struct {
	MaxSize    int  `yaml:"maxSize"`
	MaxAge     int  `yaml:"maxAge"`
	MaxBackups int  `yaml:"maxBackups"`
	Compress   bool `yaml:"compress"`
}

RotationConfig 日志轮转配置

type Settings

type Settings struct {
	Settings Config `yaml:"settings"`
	// contains filtered or unexported fields
}

Settings 兼容原先的配置结构

func (*Settings) Init

func (e *Settings) Init()

func (*Settings) OnChange

func (e *Settings) OnChange()

type Ssl

type Ssl struct {
	KeyStr string
	Pem    string
	Enable bool
	Domain string
}

type Tls

type Tls struct {
	Cert string `yaml:"cert" json:"cert"`
	Key  string `yaml:"key" json:"key"`
	Ca   string `yaml:"ca" json:"ca"`
}

Tls points at the certificate files for an encrypted connection.

Jump to

Keyboard shortcuts

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