Leggere file TOML in Swift
In questo articolo vediamo come leggere un file TOML in Swift.
Useremo swift-toml come libreria.
Per prima cosa aggiungiamo la dipendenza al Package.swift:
// swift-tools-version: 6.2
import PackageDescription
let package = Package(
name: "test_swift",
dependencies: [
.package(url: "https://github.com/jdfergason/swift-toml", from: "1.0.0")
],
targets: [
.executableTarget(
name: "test_swift",
dependencies: [
.product(name: "Toml", package: "swift-toml")
]
)
]
)
Questo il file TOML:
title = "Test TOML"
version = "1.0.0"
[database]
host = "localhost"
port = 5432
username = "root"
password = "password"
databases = ["db_test"]
pool_size = 10
ssl_enabled = true
[server]
host = "0.0.0.0"
port = 8080
debug = false
allowed_hosts = ["*"]
[logging]
level = "INFO"
format = "%(asctime)s - %(levelname)s - %(message)s"
handlers = ["console", "file"]
[cache]
enabled = true
ttl = 3600
max_size = 1000
[features]
enable_api = true
rate_limit = 100
Questo il codice di esempio:
import Foundation
import Toml
// Strutture per mappare i dati TOML
struct Config {
let title: String
let version: String
let database: Database
let server: Server
let logging: Logging
let cache: Cache
let features: Features
}
struct Database {
let host: String
let port: Int
let username: String
let password: String
let databases: [String]
let poolSize: Int
let sslEnabled: Bool
}
struct Server {
let host: String
let port: Int
let debug: Bool
let allowedHosts: [String]
}
struct Logging {
let level: String
let format: String
let handlers: [String]
}
struct Cache {
let enabled: Bool
let ttl: Int
let maxSize: Int
}
struct Features {
let enableApi: Bool
let rateLimit: Int
}
func readTomlFile(path: String) throws -> Config {
// Legge il contenuto del file
let fileContent = try String(contentsOfFile: path, encoding: .utf8)
// Parse del TOML
guard let toml = try? Toml(withString: fileContent) else {
throw NSError(
domain: "TOMLError", code: 1,
userInfo: [NSLocalizedDescriptionKey: "Errore nel parsing del file TOML"])
}
// Estrazione dei valori principali
guard let title = toml.string("title"),
let version = toml.string("version")
else {
throw NSError(
domain: "TOMLError", code: 2,
userInfo: [NSLocalizedDescriptionKey: "Campi title o version mancanti"])
}
// Estrazione sezione database
let database = Database(
host: toml.string("database.host") ?? "localhost",
port: toml.int("database.port") ?? 5432,
username: toml.string("database.username") ?? "",
password: toml.string("database.password") ?? "",
databases: toml.array("database.databases") ?? [],
poolSize: toml.int("database.pool_size") ?? 10,
sslEnabled: toml.bool("database.ssl_enabled") ?? false
)
// Estrazione sezione server
let server = Server(
host: toml.string("server.host") ?? "0.0.0.0",
port: toml.int("server.port") ?? 8080,
debug: toml.bool("server.debug") ?? false,
allowedHosts: toml.array("server.allowed_hosts") ?? []
)
// Estrazione sezione logging
let logging = Logging(
level: toml.string("logging.level") ?? "INFO",
format: toml.string("logging.format") ?? "",
handlers: toml.array("logging.handlers") ?? []
)
// Estrazione sezione cache
let cache = Cache(
enabled: toml.bool("cache.enabled") ?? true,
ttl: toml.int("cache.ttl") ?? 3600,
maxSize: toml.int("cache.max_size") ?? 1000
)
// Estrazione sezione features
let features = Features(
enableApi: toml.bool("features.enable_api") ?? true,
rateLimit: toml.int("features.rate_limit") ?? 100
)
return Config(
title: title,
version: version,
database: database,
server: server,
logging: logging,
cache: cache,
features: features
)
}
// Funzione per stampare la configurazione
func printConfig(_ config: Config) {
print("=== Configurazione ===")
print("Title: \(config.title)")
print("Version: \(config.version)")
print()
print("=== Database ===")
print("Host: \(config.database.host)")
print("Port: \(config.database.port)")
print("Username: \(config.database.username)")
print("Databases: \(config.database.databases)")
print("Pool Size: \(config.database.poolSize)")
print("SSL Enabled: \(config.database.sslEnabled)")
print()
print("=== Server ===")
print("Host: \(config.server.host)")
print("Port: \(config.server.port)")
print("Debug: \(config.server.debug)")
print("Allowed Hosts: \(config.server.allowedHosts)")
print()
print("=== Logging ===")
print("Level: \(config.logging.level)")
print("Format: \(config.logging.format)")
print("Handlers: \(config.logging.handlers)")
print()
print("=== Cache ===")
print("Enabled: \(config.cache.enabled)")
print("TTL: \(config.cache.ttl)")
print("Max Size: \(config.cache.maxSize)")
print()
print("=== Features ===")
print("Enable API: \(config.features.enableApi)")
print("Rate Limit: \(config.features.rateLimit)")
}
// Esempio di utilizzo
do {
let config = try readTomlFile(path: "test.toml")
printConfig(config)
} catch {
print("Errore nella lettura del file TOML: \(error)")
}
Enjoy!
swift toml swift-toml
Commentami!