Variáveis de Ambiente (std::env)
Nesta página
std::env segue o modelo 12-factor: a configuração vem do ambiente. O módulo
oferece leitura/escrita de variáveis individuais, enumeração de todo o ambiente,
e funções de plataforma como env.os() e env.arch(). Como interage com o
processo do host, não pode ser executado no sandbox WASM; use a CLI do Zolo.
Ler, definir e remover variáveis
env.get(name) retorna a string do valor ou nil quando a variável não existe.
O operador ?? é o idioma natural para defaults. env.set e env.remove
modificam o ambiente do processo atual:
Lê PATH, aplica default com ??, define APP_NAME e depois remove.
// Feature: env.get / env.set — environment variables
// When to use: env-driven config (12-factor), feature flags, secrets.
use std::env
// env.get(name) -> string or nil if not present.
let path = env.get("PATH")
print(path != nil) // expected: true
let missing = env.get("VARIABLE_THAT_DOES_NOT_EXIST_42")
print(missing) // expected: nil
// Idiomatic pattern: default via `??`.
let port = env.get("APP_PORT") ?? "8080"
print(port) // expected: 8080 (if APP_PORT not set)
// env.set(name, value) modifies the current process environment.
env.set("APP_NAME", "zolo")
print(env.get("APP_NAME")) // expected: zolo
// env.remove undoes it.
env.remove("APP_NAME")
print(env.get("APP_NAME")) // expected: nil
Requer a CLI/host do Zolo — abra no playground ou rode localmente.
Enumerar o ambiente e consultar o sistema
env.all() retorna uma tabela com todas as variáveis. env.os(), env.arch()
e env.home_dir() expõem informações do sistema operacional úteis em scripts
multiplataforma:
Lê PATH de env.all(), imprime OS, arquitetura e diretório home.
// Feature: env.all / env.os / env.arch / env.home_dir — environment info
// When to use: cross-platform scripts, debugging, picking paths per OS.
use std::Map
use std::env
// env.all() -> plain table mapping VAR=value. Use Map.from to wrap
// it in a Map object, or index it directly with `[name]`.
let all = env.all()
let path = all["PATH"]
let has_path = path != nil
print(has_path) // expected: true
// Current OS: "windows", "linux", "macos".
// (`os` shadows the Lua-builtin module of the same name; pick a
// different identifier to be safe.)
let cur_os = env.os()
print(cur_os.len() > 0) // expected: true
// Architecture: "x64", "arm64", etc.
let cur_arch = env.arch()
print(cur_arch.len() > 0) // expected: true
// User's home directory (nil only on very unusual setups).
let home = env.home_dir()
let has_home = home != nil
print(has_home) // expected: true
Requer a CLI/host do Zolo — abra no playground ou rode localmente.
Padrão: struct de configuração
O padrão recomendado para aplicações 12-factor é centralizar todos os defaults
em uma struct Config e carregá-la uma vez na inicialização, com funções
auxiliares para converter strings em inteiros e booleanos:
Define Config com port, log_level, debug e database_url via variáveis de ambiente.
// Feature: env — idiomatic pattern for loading configuration
// When to use: 12-factor applications read config from env vars.
use std::string
use std::env
// Define a config struct to centralize all defaults.
struct Config {
port: int,
log_level: str,
debug: bool,
database_url: str,
}
fn parse_int(s: str?, default_v: int) -> int {
if s == nil { return default_v }
let n = string::to_int(s)
if n == nil { return default_v }
return n
}
fn parse_bool(s: str?) -> bool {
if s == nil { return false }
return s == "true" || s == "1" || s == "yes"
}
fn load_config() -> Config {
return Config { port: parse_int(env.get("APP_PORT"), 8080), log_level: env.get("APP_LOG_LEVEL") ?? "info", debug: parse_bool(env.get("APP_DEBUG")), database_url: env.get("DATABASE_URL") ?? "postgres://localhost/dev" }
}
let cfg = load_config()
print(cfg.port) // expected: 8080 (default)
print(cfg.log_level) // expected: info (default)
Requer a CLI/host do Zolo — abra no playground ou rode localmente.
Desafio
Defina APP_PORT=3000 antes de executar e verifique que cfg.port muda de
8080 para 3000.