RustアプリケーションのTOML設定からJSONへの変換
RustアプリケーションのTOML設定ファイルをJSONに変換します。configクレートのパターン、環境別設定、serdeデシリアライゼーションのマッピングを解説します。
Real-World Configs
詳細な説明
Rustアプリケーションは config クレートや手動の toml クレート解析を通じて、TOMLを設定に一般的に使用します。JSON等価物を理解することは、相互運用性、APIレスポンス、多言語環境で価値があります。
RustアプリケーションのTOML設定:
[app]
name = "web-service"
version = "2.1.0"
debug = false
[server]
host = "0.0.0.0"
port = 8080
workers = 4
max_connections = 1000
request_timeout = 30
[server.tls]
enabled = true
cert_path = "/etc/ssl/server.crt"
key_path = "/etc/ssl/server.key"
[database]
url = "postgres://user:pass@db:5432/myapp"
max_pool_size = 20
min_pool_size = 5
connect_timeout = 10
idle_timeout = 300
[database.migrations]
auto_run = true
directory = "./migrations"
[logging]
level = "info"
format = "json"
file = "/var/log/app.log"
[cache]
backend = "redis"
url = "redis://cache:6379"
ttl = 3600
prefix = "myapp:"
JSONに変換すると:
{
"app": {
"name": "web-service",
"version": "2.1.0",
"debug": false
},
"server": {
"host": "0.0.0.0",
"port": 8080,
"workers": 4,
"max_connections": 1000,
"request_timeout": 30,
"tls": {
"enabled": true,
"cert_path": "/etc/ssl/server.crt",
"key_path": "/etc/ssl/server.key"
}
},
"database": {
"url": "postgres://user:pass@db:5432/myapp",
"max_pool_size": 20,
"min_pool_size": 5,
"connect_timeout": 10,
"idle_timeout": 300,
"migrations": {
"auto_run": true,
"directory": "./migrations"
}
},
"logging": {
"level": "info",
"format": "json",
"file": "/var/log/app.log"
},
"cache": {
"backend": "redis",
"url": "redis://cache:6379",
"ttl": 3600,
"prefix": "myapp:"
}
}
このパターンがRustで一般的な理由:
serdeクレートはTOMLテーブルをRust構造体に直接マッピングします。各[section]が構造体フィールドになります。- TOMLの整数型(
port = 8080)はRustのi64に正確にマッピングされ、その後JSON数値になります。 configクレートはレイヤード設定をサポートします:TOMLベースファイル + 環境変数 + JSONオーバーライド。
実用的な変換の注意点:
- スネークケースキー(
max_pool_size)はRustとTOMLの両方で慣用的です。JSONでもそのまま残ります。 - サブテーブル(
[server.tls]、[database.migrations])はネストされたRust構造体にマッピングされるネストされたオブジェクトを作成します。 - null値はない。 Rustの
Option<T>フィールドでNoneの場合、TOMLファイルからは単純に省略されます。JSONではnullとして表示されるか、不在になる可能性があります。
ユースケース
TOMLを設定に使用するRustマイクロサービスを運用し、/configヘルスチェックエンドポイントを通じて有効な設定をJSONとして公開する場合。またはRustとNode.jsサービス間で設定を共有する場合。