Use json configuration

Delete paths.conf
This commit is contained in:
Christoph Hagen 2022-05-22 23:24:04 +02:00
parent 09046bb320
commit ce1e141ca4
4 changed files with 42 additions and 21 deletions

4
Resources/config.json Normal file
View File

@ -0,0 +1,4 @@
{
"logPath": "\/var\/log\/caps.log",
"serveFiles": true
}

View File

@ -1,2 +0,0 @@
/data/logs/caps/server.log
/data/servers/caps/Public

16
Sources/App/Config.swift Normal file
View File

@ -0,0 +1,16 @@
import Foundation
struct Config: Codable {
let logPath: String
let serveFiles: Bool
var logURL: URL {
.init(fileURLWithPath: logPath)
}
static var `default`: Config {
.init(logPath: "/var/log/caps.log", serveFiles: true)
}
}

View File

@ -1,35 +1,38 @@
import Vapor import Vapor
import Foundation
private(set) var server: CapServer! private(set) var server: CapServer!
// configures your application
public func configure(_ app: Application) throws { public func configure(_ app: Application) throws {
// uncomment to serve files from /Public folder
// app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
app.http.server.configuration.port = 6001 app.http.server.configuration.port = 6001
app.routes.defaultMaxBodySize = "2mb" app.routes.defaultMaxBodySize = "2mb"
let configFile = URL(fileURLWithPath: app.directory.resourcesDirectory) let configFile = URL(fileURLWithPath: app.directory.resourcesDirectory)
.appendingPathComponent("paths.conf") .appendingPathComponent("config.json")
let configData = try String(contentsOf: configFile) let config: Config
.components(separatedBy: "\n") if !FileManager.default.fileExists(atPath: configFile.path) {
.map { $0.trimmingCharacters(in: .whitespaces) } config = .default
.filter { !$0.isEmpty } let configData = try JSONEncoder().encode(config)
guard configData.count >= 2 else { try configData.write(to: configFile)
print("Invalid configuration file: \(configData.count) lines") print("Wrote default configuration")
throw CapError.invalidConfiguration } else {
let configData = try Data(contentsOf: configFile)
config = try JSONDecoder().decode(Config.self, from: configData)
} }
let logFile = URL(fileURLWithPath: configData[0])
let publicDirectory = URL(fileURLWithPath: configData[1])
try Log.set(logFile: logFile.path) try Log.set(logFile: config.logPath)
server = try CapServer(in: publicDirectory) let publicDirectory = app.directory.publicDirectory
if config.serveFiles {
let middleware = FileMiddleware(publicDirectory: publicDirectory)
app.middleware.use(middleware)
}
server = try CapServer(in: URL(fileURLWithPath: publicDirectory))
try server.loadCapNames() try server.loadCapNames()
// Register routes to the router // Register routes to the router
try routes(app) try routes(app)
// Configure the rest of your application here
} }