App.swift 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //
  2. // App.swift
  3. // Swifter
  4. //
  5. // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
  6. //
  7. import Foundation
  8. public class App {
  9. private let server = HttpServer()
  10. public init() { }
  11. public func run(port: in_port_t = 9080, _ databasePath: String) throws -> Void {
  12. // Open database connection.
  13. DatabaseReflection.sharedDatabase = try SQLite.open(databasePath)
  14. defer {
  15. DatabaseReflection.sharedDatabase?.close()
  16. }
  17. // Watch process signals.
  18. Process.watchSignals { switch $0 {
  19. case SIGTERM, SIGINT:
  20. self.server.stop()
  21. DatabaseReflection.sharedDatabase?.close()
  22. exit(EXIT_SUCCESS)
  23. case SIGINFO:
  24. print("Swifter Version: \(HttpServer.VERSION)")
  25. print(self.server.routes.joined(separator: "\n"))
  26. case SIGHUP:
  27. print("//TODO - Reload config.")
  28. default:
  29. print("Unknown signal received: \(signal).")
  30. }
  31. }
  32. // Add simple logging.
  33. self.server.middleware.append({ r in
  34. print("\(r.method) - \(r.path)")
  35. return nil
  36. })
  37. // Boot the server.
  38. print("Starting Swifter (\(HttpServer.VERSION)) at port \(port) with PID \(Process.PID)...")
  39. try self.server.start(port)
  40. print("Server started. Waiting for requests....")
  41. NSRunLoop.main().run()
  42. }
  43. }