Files.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //
  2. // HttpHandlers+Files.swift
  3. // Swifter
  4. //
  5. // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
  6. //
  7. import Foundation
  8. public func shareFilesFromDirectory(_ directoryPath: String, defaults: [String] = ["index.html", "default.html"]) -> ((HttpRequest) -> HttpResponse) {
  9. return { r in
  10. guard let fileRelativePath = r.params.first else {
  11. return .notFound
  12. }
  13. if fileRelativePath.value.isEmpty {
  14. for path in defaults {
  15. if let file = try? (directoryPath + String.pathSeparator + path).openForReading() {
  16. return .raw(200, "OK", [:], { writer in
  17. try? writer.write(file)
  18. file.close()
  19. })
  20. }
  21. }
  22. }
  23. if let file = try? (directoryPath + String.pathSeparator + fileRelativePath.value).openForReading() {
  24. return .raw(200, "OK", [:], { writer in
  25. try? writer.write(file)
  26. file.close()
  27. })
  28. }
  29. return .notFound
  30. }
  31. }
  32. public func directoryBrowser(_ dir: String) -> ((HttpRequest) -> HttpResponse) {
  33. return { r in
  34. guard let (_, value) = r.params.first else {
  35. return HttpResponse.notFound
  36. }
  37. let filePath = dir + String.pathSeparator + value
  38. do {
  39. guard try filePath.exists() else {
  40. return .notFound
  41. }
  42. if try filePath.directory() {
  43. let files = try filePath.files()
  44. return scopes {
  45. html {
  46. body {
  47. table(files) { file in
  48. tr {
  49. td {
  50. a {
  51. href = r.path + "/" + file
  52. inner = file
  53. }
  54. }
  55. }
  56. }
  57. }
  58. }
  59. }(r)
  60. } else {
  61. guard let file = try? filePath.openForReading() else {
  62. return .notFound
  63. }
  64. return .raw(200, "OK", [:], { writer in
  65. try? writer.write(file)
  66. file.close()
  67. })
  68. }
  69. } catch {
  70. return HttpResponse.internalServerError
  71. }
  72. }
  73. }