Skip to main content
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
}
Load
func() error
Loads configuration from all sources and starts watching for changes
Scan
func(v any) error
Scans the entire configuration into the provided struct
Value
func(key string) Value
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
Close
func() error
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
Watch
func() (Watcher, error)
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
Stop
func() error
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
}
Key
string
Configuration key
Value
[]byte
Configuration value as bytes
Format
string
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
opts
...Option
Configuration options
config
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
s
...Source
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
d
Decoder
Custom decoder function

WithResolver

Sets a custom resolver for placeholder expansion.
func WithResolver(r Resolver) Option
r
Resolver
Custom resolver function

WithResolveActualTypes

Enables automatic type conversion.
func WithResolveActualTypes(enableConvertToType bool) Option
enableConvertToType
bool
Whether to enable type conversion

WithMergeFunc

Sets a custom merge function for combining multiple sources.
func WithMergeFunc(m Merge) Option
m
Merge
Custom merge function

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
    ),
)

Build docs developers (and LLMs) love