HttpHandlers.swift 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //
  2. // Handlers.swift
  3. // Swifter
  4. // Copyright (c) 2014 Damian Kołakowski. All rights reserved.
  5. //
  6. import Foundation
  7. class HttpHandlers {
  8. 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, fileBody)
  14. }
  15. }
  16. return HttpResponse.NotFound
  17. }
  18. }
  19. 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 += "".join(files.map { "<tr><td><a href=\"\(request.url)/\($0)\">\($0)</a></td></tr>"} )
  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, fileBody)
  39. }
  40. }
  41. }
  42. }
  43. return HttpResponse.NotFound
  44. }
  45. }
  46. }