1
0

Files.swift 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 { _ 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 { request in
  21. guard let fileRelativePath = request.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. let mimeType = fileRelativePath.value.mimeType()
  36. return .raw(200, "OK", ["Content-Type": mimeType], { 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 { request in
  46. guard let (_, value) = request.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. var files = try filePath.files()
  56. files.sort(by: {$0.lowercased() < $1.lowercased()})
  57. return scopes {
  58. html {
  59. body {
  60. table(files) { file in
  61. tr {
  62. td {
  63. a {
  64. href = request.path + "/" + file
  65. inner = file
  66. }
  67. }
  68. }
  69. }
  70. }
  71. }
  72. }(request)
  73. } else {
  74. guard let file = try? filePath.openForReading() else {
  75. return .notFound
  76. }
  77. return .raw(200, "OK", [:], { writer in
  78. try? writer.write(file)
  79. file.close()
  80. })
  81. }
  82. } catch {
  83. return HttpResponse.internalServerError
  84. }
  85. }
  86. }