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