1
0

Files.swift 2.5 KB

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