1
0

Files.swift 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 shareFile(_ path: String) -> ((HttpRequest) -> HttpResponse) {
  9. return { r in
  10. if let file = try? path.openForReading() {
  11. return .raw(200, "OK", [:], { writer in
  12. try? writer.write(file)
  13. file.close()
  14. })
  15. }
  16. return .notFound
  17. }
  18. }
  19. public func shareFilesFromDirectory(_ directoryPath: String, defaults: [String] = ["index.html", "default.html"]) -> ((HttpRequest) -> HttpResponse) {
  20. return { r in
  21. guard let fileRelativePath = r.params.first else {
  22. return .notFound
  23. }
  24. if fileRelativePath.value.isEmpty {
  25. for path in defaults {
  26. if let file = try? (directoryPath + String.pathSeparator + path).openForReading() {
  27. return .raw(200, "OK", [:], { writer in
  28. try? writer.write(file)
  29. file.close()
  30. })
  31. }
  32. }
  33. }
  34. if let file = try? (directoryPath + String.pathSeparator + fileRelativePath.value).openForReading() {
  35. return .raw(200, "OK", [:], { writer in
  36. try? writer.write(file)
  37. file.close()
  38. })
  39. }
  40. return .notFound
  41. }
  42. }
  43. public func directoryBrowser(_ dir: String) -> ((HttpRequest) -> HttpResponse) {
  44. return { r in
  45. guard let (_, value) = r.params.first else {
  46. return HttpResponse.notFound
  47. }
  48. let filePath = dir + String.pathSeparator + value
  49. do {
  50. guard try filePath.exists() else {
  51. return .notFound
  52. }
  53. if try filePath.directory() {
  54. let files = try filePath.files()
  55. return scopes {
  56. html {
  57. body {
  58. table(files) { file in
  59. tr {
  60. td {
  61. a {
  62. href = r.path + "/" + file
  63. inner = file
  64. }
  65. }
  66. }
  67. }
  68. }
  69. }
  70. }(r)
  71. } else {
  72. guard let file = try? filePath.openForReading() else {
  73. return .notFound
  74. }
  75. return .raw(200, "OK", [:], { writer in
  76. try? writer.write(file)
  77. file.close()
  78. })
  79. }
  80. } catch {
  81. return HttpResponse.internalServerError
  82. }
  83. }
  84. }