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 Foundation
private(set) var server: CapServer!
// configures your application
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.routes.defaultMaxBodySize = "2mb"
let configFile = URL(fileURLWithPath: app.directory.resourcesDirectory)
.appendingPathComponent("paths.conf")
let configData = try String(contentsOf: configFile)
.components(separatedBy: "\n")
.map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
guard configData.count >= 2 else {
print("Invalid configuration file: \(configData.count) lines")
throw CapError.invalidConfiguration
.appendingPathComponent("config.json")
let config: Config
if !FileManager.default.fileExists(atPath: configFile.path) {
config = .default
let configData = try JSONEncoder().encode(config)
try configData.write(to: configFile)
print("Wrote default configuration")
} 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)
server = try CapServer(in: publicDirectory)
try Log.set(logFile: config.logPath)
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()
// Register routes to the router
try routes(app)
// Configure the rest of your application here
}