JSONConfig 简体中文

这是一个基于JSON的简单配置库,用于Perfect框架。

这个库允许你更灵活地组织配置,而不是使用扁平的JSON文件来满足你的配置需求。

设置

在你的项目的 Package.swift 文件中包含 JSONConfig 依赖。

.package(url: "https://github.com/AutomatonTec/JSONConfig.git", from: "1.1.3")

// section dependencies
dependencies: ["JSONConfig"]

在更改 Package.swift 文件后,重新构建你的 Xcode 项目。

swift package generate-xcodeproj

使用示例

import JSONConfig
// somewhere, perhaps in main.swift, determine the path to your config file

let configServerDefaults = "./config/server/common.json"
#if os(Linux)
    let configServer = "./config/server/linux.json"
#else
    let configServer = "./config/server/macOS.json"
#endif

let config = JSONConfig(withJsonAt:configServer, defaultsInJsonAt:configServerDefaults)

// somewhere, anywhere
func setupDatabase(withConfig config:JSONConfig) {
    MySQLConnector.host     = config.string(forKeyPath: "database.host", otherwise: "127.0.0.1")
    MySQLConnector.username = config.string(forKeyPath: "database.username", otherwise: "db_user")
    MySQLConnector.password = config.string(forKeyPath: "database.password", otherwise: "best_password")
    MySQLConnector.database = config.string(forKeyPath: "database.database", otherwise: "db_user")
}

func setupServer(withConfig config:JSONConfig, server:HTTPServer) {
    server.serverName = config.string(forKeyPath: "server.name", otherwise: "sub.your-domain.com")
    server.serverPort = UInt16(config.integer(forKeyPath: "server.port", otherwise: 8080))
}

在你的通用 JSON 配置文件中,你可能拥有如下内容:

{
	"server": {
		"name" : "api.your-domain.com",
		"port" : 80
	},
    "database": {
        "host":     "127.0.0.1",
        "username": "db_bob",
        "password": "bob_password",
        "database": "db_bob"
    }
}

在你的 macOS JSON 配置文件中,你可能拥有如下内容:

{
	"server": {
		"name" : "localhost",
		"port" : 8181
	}
}