HttpHandlers.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 directory(dir: String) -> ( HttpRequest -> HttpResponse ) {
  9. return { request in
  10. if let localPath = request.capturedUrlGroups.first {
  11. let filesPath = dir.stringByExpandingTildeInPath.stringByAppendingPathComponent(localPath)
  12. if let fileBody = NSData(contentsOfFile: filesPath) {
  13. return HttpResponse.RAW(200, "OK", nil, fileBody)
  14. }
  15. }
  16. return HttpResponse.NotFound
  17. }
  18. }
  19. public class func directoryBrowser(dir: String) -> ( HttpRequest -> HttpResponse ) {
  20. return { request in
  21. if let pathFromUrl = request.capturedUrlGroups.first {
  22. let filePath = dir.stringByExpandingTildeInPath.stringByAppendingPathComponent(pathFromUrl)
  23. let fileManager = NSFileManager.defaultManager()
  24. var isDir: ObjCBool = false;
  25. if fileManager.fileExistsAtPath(filePath, isDirectory: &isDir) {
  26. if isDir {
  27. do {
  28. let files = try fileManager.contentsOfDirectoryAtPath(filePath)
  29. var response = "<h3>\(filePath)</h3></br><table>"
  30. response += files.map({ "<tr><td><a href=\"\(request.url)/\($0)\">\($0)</a></td></tr>"}).joinWithSeparator("")
  31. response += "</table>"
  32. return HttpResponse.OK(.HTML(response))
  33. } catch {
  34. return HttpResponse.NotFound
  35. }
  36. } else {
  37. if let fileBody = NSData(contentsOfFile: filePath) {
  38. return HttpResponse.RAW(200, "OK", nil, fileBody)
  39. }
  40. }
  41. }
  42. }
  43. return HttpResponse.NotFound
  44. }
  45. }
  46. }
  47. private extension String {
  48. var stringByExpandingTildeInPath: String {
  49. return (self as NSString).stringByExpandingTildeInPath
  50. }
  51. func stringByAppendingPathComponent(str: String) -> String {
  52. return (self as NSString).stringByAppendingPathComponent(str)
  53. }
  54. }