HttpHandlers.swift 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //
  2. // Handlers.swift
  3. // Swifter
  4. // Copyright (c) 2015 Damian Kołakowski. All rights reserved.
  5. //
  6. import Foundation
  7. public class HttpHandlers {
  8. public class func file(path: String) -> ( HttpRequest -> HttpResponse ) {
  9. return { request in
  10. let filesPath = path.stringByExpandingTildeInPath
  11. if let fileBody = NSData(contentsOfFile: filesPath) {
  12. return HttpResponse.RAW(200, "OK", nil, fileBody)
  13. }
  14. return HttpResponse.NotFound
  15. }
  16. }
  17. public class func directory(dir: String) -> ( HttpRequest -> HttpResponse ) {
  18. return { request in
  19. if let localPath = request.capturedUrlGroups.first {
  20. let filesPath = dir.stringByExpandingTildeInPath.stringByAppendingPathComponent(localPath)
  21. if let fileBody = NSData(contentsOfFile: filesPath) {
  22. return HttpResponse.RAW(200, "OK", nil, fileBody)
  23. }
  24. }
  25. return HttpResponse.NotFound
  26. }
  27. }
  28. public class func directoryBrowser(dir: String) -> ( HttpRequest -> HttpResponse ) {
  29. return { request in
  30. if let pathFromUrl = request.capturedUrlGroups.first {
  31. let filePath = dir.stringByExpandingTildeInPath.stringByAppendingPathComponent(pathFromUrl)
  32. let fileManager = NSFileManager.defaultManager()
  33. var isDir: ObjCBool = false;
  34. if fileManager.fileExistsAtPath(filePath, isDirectory: &isDir) {
  35. if isDir {
  36. do {
  37. let files = try fileManager.contentsOfDirectoryAtPath(filePath)
  38. var response = "<h3>\(filePath)</h3></br><table>"
  39. response += files.map({ "<tr><td><a href=\"\(request.url)/\($0)\">\($0)</a></td></tr>"}).joinWithSeparator("")
  40. response += "</table>"
  41. return HttpResponse.OK(.Html(response))
  42. } catch {
  43. return HttpResponse.NotFound
  44. }
  45. } else {
  46. if let fileBody = NSData(contentsOfFile: filePath) {
  47. return HttpResponse.RAW(200, "OK", nil, fileBody)
  48. }
  49. }
  50. }
  51. }
  52. return HttpResponse.NotFound
  53. }
  54. }
  55. }
  56. private extension String {
  57. var stringByExpandingTildeInPath: String {
  58. return (self as NSString).stringByExpandingTildeInPath
  59. }
  60. func stringByAppendingPathComponent(str: String) -> String {
  61. return (self as NSString).stringByAppendingPathComponent(str)
  62. }
  63. }