|
@@ -10,6 +10,8 @@ public class HttpHandlers {
|
|
|
|
|
|
|
|
private static let rangeExpression = try! NSRegularExpression(pattern: "bytes=(\\d*)-(\\d*)", options: .CaseInsensitive)
|
|
private static let rangeExpression = try! NSRegularExpression(pattern: "bytes=(\\d*)-(\\d*)", options: .CaseInsensitive)
|
|
|
|
|
|
|
|
|
|
+ private static let cache = NSCache()
|
|
|
|
|
+
|
|
|
public class func directory(dir: String) -> ( HttpRequest -> HttpResponse ) {
|
|
public class func directory(dir: String) -> ( HttpRequest -> HttpResponse ) {
|
|
|
return { request in
|
|
return { request in
|
|
|
|
|
|
|
@@ -19,10 +21,16 @@ public class HttpHandlers {
|
|
|
|
|
|
|
|
let filesPath = dir.stringByExpandingTildeInPath.stringByAppendingPathComponent(localPath)
|
|
let filesPath = dir.stringByExpandingTildeInPath.stringByAppendingPathComponent(localPath)
|
|
|
|
|
|
|
|
- guard let fileBody = NSData(contentsOfFile: filesPath) else {
|
|
|
|
|
|
|
+ let cachedBody = cache.objectForKey(filesPath) as? NSData
|
|
|
|
|
+
|
|
|
|
|
+ guard let fileBody = cachedBody ?? NSData(contentsOfFile: filesPath) else {
|
|
|
return HttpResponse.NotFound
|
|
return HttpResponse.NotFound
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ if cachedBody == nil {
|
|
|
|
|
+ cache.setObject(fileBody, forKey: filesPath)
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
if let rangeHeader = request.headers["range"] {
|
|
if let rangeHeader = request.headers["range"] {
|
|
|
|
|
|
|
|
guard let match = rangeExpression.matchesInString(rangeHeader, options: .Anchored, range: NSRange(location: 0, length: rangeHeader.characters.count)).first where match.numberOfRanges == 3 else {
|
|
guard let match = rangeExpression.matchesInString(rangeHeader, options: .Anchored, range: NSRange(location: 0, length: rangeHeader.characters.count)).first where match.numberOfRanges == 3 else {
|
|
@@ -49,8 +57,6 @@ public class HttpHandlers {
|
|
|
"Content-Range" : "bytes \(startStr)-\(endStr)/\(fileBody.length)"
|
|
"Content-Range" : "bytes \(startStr)-\(endStr)/\(fileBody.length)"
|
|
|
]
|
|
]
|
|
|
|
|
|
|
|
- print(rangeHeader, headers)
|
|
|
|
|
-
|
|
|
|
|
return HttpResponse.RAW(206, "Partial Content", headers, subData)
|
|
return HttpResponse.RAW(206, "Partial Content", headers, subData)
|
|
|
|
|
|
|
|
}
|
|
}
|