| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- //
- // Handlers.swift
- // Swifter
- // Copyright (c) 2015 Damian Kołakowski. All rights reserved.
- //
- import Foundation
- public class HttpHandlers {
-
- public class func file(path: String) -> ( HttpRequest -> HttpResponse ) {
- return { request in
- let filesPath = path.stringByExpandingTildeInPath
- if let fileBody = NSData(contentsOfFile: filesPath) {
- return HttpResponse.RAW(200, "OK", nil, fileBody)
- }
- return HttpResponse.NotFound
- }
- }
- public class func directory(dir: String) -> ( HttpRequest -> HttpResponse ) {
- return { request in
- if let localPath = request.capturedUrlGroups.first {
- let filesPath = dir.stringByExpandingTildeInPath.stringByAppendingPathComponent(localPath)
- if let fileBody = NSData(contentsOfFile: filesPath) {
- return HttpResponse.RAW(200, "OK", nil, fileBody)
- }
- }
- return HttpResponse.NotFound
- }
- }
- public class func directoryBrowser(dir: String) -> ( HttpRequest -> HttpResponse ) {
- return { request in
- if let pathFromUrl = request.capturedUrlGroups.first {
- let filePath = dir.stringByExpandingTildeInPath.stringByAppendingPathComponent(pathFromUrl)
- let fileManager = NSFileManager.defaultManager()
- var isDir: ObjCBool = false;
- if fileManager.fileExistsAtPath(filePath, isDirectory: &isDir) {
- if isDir {
- do {
- let files = try fileManager.contentsOfDirectoryAtPath(filePath)
- var response = "<h3>\(filePath)</h3></br><table>"
- response += files.map({ "<tr><td><a href=\"\(request.url)/\($0)\">\($0)</a></td></tr>"}).joinWithSeparator("")
- response += "</table>"
- return HttpResponse.OK(.Html(response))
- } catch {
- return HttpResponse.NotFound
- }
- } else {
- if let fileBody = NSData(contentsOfFile: filePath) {
- return HttpResponse.RAW(200, "OK", nil, fileBody)
- }
- }
- }
- }
- return HttpResponse.NotFound
- }
- }
- }
- private extension String {
- var stringByExpandingTildeInPath: String {
- return (self as NSString).stringByExpandingTildeInPath
- }
- func stringByAppendingPathComponent(str: String) -> String {
- return (self as NSString).stringByAppendingPathComponent(str)
- }
- }
|