Files.swift 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. var files = try filePath.files()
  55. files.sort(by: {$0.lowercased() < $1.lowercased()})
  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. }