Files.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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) -> ((HttpRequest) -> HttpResponse) {
  13. return { r in
  14. guard let fileRelativePath = r.params.first else {
  15. return .notFound
  16. }
  17. let absolutePath = directoryPath + "/" + fileRelativePath.1
  18. guard let file = try? File.openForReading(absolutePath) else {
  19. return .notFound
  20. }
  21. return .raw(200, "OK", [:], { writer in
  22. defer { file.close() }
  23. try writer.write(file)
  24. })
  25. }
  26. }
  27. public func directoryBrowser(_ dir: String) -> ((HttpRequest) -> HttpResponse) {
  28. return { r in
  29. guard let (_, value) = r.params.first else {
  30. return HttpResponse.notFound
  31. }
  32. let filePath = dir + "/" + value
  33. do {
  34. guard try File.exists(filePath) else {
  35. return HttpResponse.notFound
  36. }
  37. if try File.isDirectory(filePath) {
  38. let files = try File.list(filePath)
  39. return scopes {
  40. html {
  41. body {
  42. table(files) { file in
  43. tr {
  44. td {
  45. a {
  46. href = r.path + "/" + file
  47. inner = file
  48. }
  49. }
  50. }
  51. }
  52. }
  53. }
  54. }(r)
  55. } else {
  56. guard let file = try? File.openForReading(filePath) else {
  57. return .notFound
  58. }
  59. return .raw(200, "OK", [:], { writer in
  60. defer { file.close() }
  61. try writer.write(file)
  62. })
  63. }
  64. } catch {
  65. return HttpResponse.internalServerError
  66. }
  67. }
  68. }