Nick Lee 10 лет назад
Родитель
Сommit
97dbad012b
1 измененных файлов с 9 добавлено и 3 удалено
  1. 9 3
      Common/HttpHandlers.swift

+ 9 - 3
Common/HttpHandlers.swift

@@ -10,6 +10,8 @@ public class HttpHandlers {
     
     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 ) {
         return { request in
             
@@ -19,10 +21,16 @@ public class HttpHandlers {
             
             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
             }
             
+            if cachedBody == nil {
+                cache.setObject(fileBody, forKey: filesPath)
+            }
+            
             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 {
@@ -49,8 +57,6 @@ public class HttpHandlers {
                     "Content-Range" : "bytes \(startStr)-\(endStr)/\(fileBody.length)"
                 ]
                 
-                print(rangeHeader, headers)
-                
                 return HttpResponse.RAW(206, "Partial Content", headers, subData)
                 
             }