1
0

HttpHandlers.swift 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. if let files = fileManager.contentsOfDirectoryAtPath(filePath, error: nil) {
  28. var response = "<h3>\(filePath)</h3></br><table>"
  29. response += join("", map(files, { "<tr><td><a href=\"\(request.url)/\($0)\">\($0)</a></td></tr>"}))
  30. response += "</table>"
  31. return HttpResponse.OK(.HTML(response))
  32. }
  33. } else {
  34. if let fileBody = NSData(contentsOfFile: filePath) {
  35. return HttpResponse.RAW(200, fileBody)
  36. }
  37. }
  38. }
  39. }
  40. return HttpResponse.NotFound
  41. }
  42. }
  43. }