HttpHandlers.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //
  2. // Handlers.swift
  3. // Swifter
  4. // Copyright (c) 2014 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. }