The Config API provides a flexible configuration management system that supports multiple sources, formats, and dynamic reloading.
Interfaces
Config
Main configuration interface.
type Config interface {
Load() error
Scan(v any) error
Value(key string) Value
Watch(key string, o Observer) error
Close() error
}
Loads configuration from all sources and starts watching for changes
Scans the entire configuration into the provided struct
Returns the value for the specified key
Watch
func(key string, o Observer) error
Watches a specific key for changes and calls the observer when changed
Closes all watchers and cleans up resources
Source
Configuration source interface.
type Source interface {
Load() ([]*KeyValue, error)
Watch() (Watcher, error)
}
Load
func() ([]*KeyValue, error)
Loads all configuration key-values from the source
Returns a watcher for monitoring source changes
Watcher
Watches a source for changes.
type Watcher interface {
Next() ([]*KeyValue, error)
Stop() error
}
Next
func() ([]*KeyValue, error)
Blocks until the next change is detected and returns the changed key-values
Stops watching and cleans up resources
Value
Represents a configuration value with type conversion methods.
type Value interface {
Bool() (bool, error)
Int() (int64, error)
Float() (float64, error)
String() (string, error)
Duration() (time.Duration, error)
Slice() ([]Value, error)
Map() (map[string]Value, error)
Scan(any) error
Load() any
Store(any)
}
Types
KeyValue
Represents a configuration key-value pair.
type KeyValue struct {
Key string
Value []byte
Format string
}
Configuration value as bytes
Format of the value (json, yaml, xml, proto, etc.)
Observer
Callback function for configuration changes.
type Observer func(string, Value)
Functions
New
Creates a new Config instance.
func New(opts ...Option) Config
Configured Config instance
Example:
import (
"github.com/go-kratos/kratos/v2/config"
"github.com/go-kratos/kratos/v2/config/file"
)
c := config.New(
config.WithSource(
file.NewSource("config.yaml"),
),
)
if err := c.Load(); err != nil {
panic(err)
}
Options
WithSource
Sets configuration sources.
func WithSource(s ...Source) Option
One or more configuration sources
Example:
config.New(
config.WithSource(
file.NewSource("config.yaml"),
env.NewSource(),
),
)
WithDecoder
Sets a custom decoder.
func WithDecoder(d Decoder) Option
WithResolver
Sets a custom resolver for placeholder expansion.
func WithResolver(r Resolver) Option
WithResolveActualTypes
Enables automatic type conversion.
func WithResolveActualTypes(enableConvertToType bool) Option
Whether to enable type conversion
WithMergeFunc
Sets a custom merge function for combining multiple sources.
func WithMergeFunc(m Merge) Option
Errors
ErrNotFound
var ErrNotFound = errors.New("key not found")
Returned when a configuration key is not found.
Usage Examples
Basic Configuration Loading
package main
import (
"fmt"
"log"
"github.com/go-kratos/kratos/v2/config"
"github.com/go-kratos/kratos/v2/config/file"
)
type Config struct {
Server struct {
HTTP struct {
Addr string `json:"addr"`
} `json:"http"`
GRPC struct {
Addr string `json:"addr"`
} `json:"grpc"`
} `json:"server"`
}
func main() {
c := config.New(
config.WithSource(
file.NewSource("config.yaml"),
),
)
defer c.Close()
if err := c.Load(); err != nil {
log.Fatal(err)
}
var cfg Config
if err := c.Scan(&cfg); err != nil {
log.Fatal(err)
}
fmt.Printf("HTTP Addr: %s\n", cfg.Server.HTTP.Addr)
}
Accessing Individual Values
// Get string value
addr := c.Value("server.http.addr").String()
// Get int value
port, err := c.Value("server.http.port").Int()
// Get bool value
enabled, err := c.Value("feature.enabled").Bool()
// Get duration
timeout, err := c.Value("server.timeout").Duration()
Watching for Changes
err := c.Watch("server.http.addr", func(key string, value config.Value) {
addr, _ := value.String()
fmt.Printf("Config changed: %s = %s\n", key, addr)
// Reload or restart service
})
if err != nil {
log.Fatal(err)
}
Using Placeholder Expansion
# config.yaml
app:
name: myapp
version: v1.0.0
server:
http:
addr: 0.0.0.0:8000
name: ${app.name}
message: "Welcome to ${app.name} ${app.version}"
c := config.New(
config.WithSource(
file.NewSource("config.yaml"),
),
)
c.Load()
// ${app.name} will be expanded to "myapp"
name := c.Value("server.name").String() // "myapp"
Multiple Sources with Priority
// Later sources override earlier ones
c := config.New(
config.WithSource(
file.NewSource("config.yaml"), // Default config
file.NewSource("config.local.yaml"), // Local overrides
env.NewSource("APP_"), // Environment overrides
),
)