Dynamic Configuration

Static config files (JSON, YAML) can only hold data. A Tengo config file can compute values, branch on environment, and derive one setting from another — all without recompiling the host application.

fmt := import("fmt")
os  := import("os")
env := os.getenv("APP_ENV")
if env == "" { env = "development" }
config := {
    env:          env,
    debug:        true,
    log_level:    "debug",
    db_host:      "localhost",
    db_port:      5432,
    db_pool:      3,
    cache_ttl:    60,
    rate_limit:   50,
    feature_dark_mode: false,
}
if env == "production" {
    config.debug      = false
    config.log_level  = "warn"
    config.db_host    = "db.prod.internal"
    config.db_pool    = 20
    config.cache_ttl  = 3600
    config.rate_limit = 2000
    config.feature_dark_mode = true
} else if env == "staging" {
    config.log_level  = "info"
    config.db_host    = "db.staging.internal"
    config.db_pool    = 8
    config.cache_ttl  = 300
}
config.db_url   = fmt.sprintf("postgres://%s:%d/app", config.db_host, config.db_port)
config.workers  = config.db_pool * 2
string_keys := ["env", "log_level", "db_url"]
other_keys  := ["debug", "workers", "cache_ttl", "rate_limit", "feature_dark_mode"]

for _, k in string_keys {
    fmt.printf("%-20s %s\n", k, config[k])
}
for _, k in other_keys {
    fmt.printf("%-20s %v\n", k, config[k])
}

try it

env                  development
log_level            debug
db_url               postgres://localhost:5432/app
debug                true
workers              6
cache_ttl            60
rate_limit           50
feature_dark_mode    false
loading…