1
0

HttpHandlers.swift 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //
  2. // Handlers.swift
  3. // Swifter
  4. //
  5. // Created by Damian Kolakowski on 14/11/14.
  6. // Copyright (c) 2014 Damian Kołakowski. All rights reserved.
  7. //
  8. import Foundation
  9. class HttpHandlers {
  10. class func directory(dir: String) -> ( HttpRequest -> HttpResponse ) {
  11. return { request in
  12. if let localPath = request.capturedUrlGroups.first {
  13. let filesPath = dir.stringByExpandingTildeInPath.stringByAppendingPathComponent(localPath)
  14. if let fileBody = NSData(contentsOfFile: filesPath) {
  15. return HttpResponse.RAW(200, fileBody)
  16. }
  17. }
  18. return HttpResponse.NotFound
  19. }
  20. }
  21. class func directoryBrowser(dir: String) -> ( HttpRequest -> HttpResponse ) {
  22. return { request in
  23. if let pathFromUrl = request.capturedUrlGroups.first {
  24. let filePath = dir.stringByExpandingTildeInPath.stringByAppendingPathComponent(pathFromUrl)
  25. let fileManager = NSFileManager.defaultManager()
  26. var isDir: ObjCBool = false;
  27. if ( fileManager.fileExistsAtPath(filePath, isDirectory: &isDir) ) {
  28. if ( isDir ) {
  29. if let files = fileManager.contentsOfDirectoryAtPath(filePath, error: nil) {
  30. var response = "<h3>\(filePath)</h3></br><table>"
  31. response += join("", map(files, { "<tr><td><a href=\"\(request.url)/\($0)\">\($0)</a></td></tr>"}))
  32. response += "</table>"
  33. return HttpResponse.OK(.HTML(response))
  34. }
  35. } else {
  36. if let fileBody = NSData(contentsOfFile: filePath) {
  37. return HttpResponse.RAW(200, fileBody)
  38. }
  39. }
  40. }
  41. }
  42. return HttpResponse.NotFound
  43. }
  44. }
  45. }