Files.swift 2.1 KB

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