Prechádzať zdrojové kódy

Added 'seek' method to 'File' class.
Added new handler for sharing files from a directory.

Damian Kołakowski 10 rokov pred
rodič
commit
0c5fd4dbf3
2 zmenil súbory, kde vykonal 26 pridanie a 0 odobranie
  1. 7 0
      Sources/File.swift
  2. 19 0
      Sources/HttpHandlers+Files.swift

+ 7 - 0
Sources/File.swift

@@ -15,6 +15,7 @@ public enum FileError: ErrorType {
     case OpenFailed(String)
     case WriteFailed(String)
     case ReadFailed(String)
+    case SeekFailed(String)
 }
 
 public class File {
@@ -77,6 +78,12 @@ public class File {
         }
     }
     
+    public func seek(offset: Int) throws -> Void {
+        if fseek(self.pointer, offset, SEEK_SET) != 0 {
+            throw FileError.SeekFailed(File.descriptionOfLastError())
+        }
+    }
+    
     private static func descriptionOfLastError() -> String {
         return String.fromCString(UnsafePointer(strerror(errno))) ?? "Error: \(errno)"
     }

+ 19 - 0
Sources/HttpHandlers+Files.swift

@@ -9,6 +9,25 @@ import Foundation
 
 extension HttpHandlers {
     
+    public class func shareFilesFromDirectory(directoryPath: String) -> (HttpRequest -> HttpResponse) {
+        return { r in
+            guard let fileRelativePath = r.params.first else {
+                return .NotFound
+            }
+            let absolutePath = directoryPath + "/" + fileRelativePath.1
+            guard let file = try? File.openForReading(absolutePath) else {
+                return .NotFound
+            }
+            return .RAW(200, "OK", [:], { writer in
+                var buffer = [UInt8](count: 64, repeatedValue: 0)
+                while let count = try? file.read(&buffer) where count > 0 {
+                    writer.write(Array(buffer[0..<count]))
+                }
+                file.close()
+            })
+        }
+    }
+    
     private static let rangePrefix = "bytes="
     
     public class func directory(dir: String) -> (HttpRequest -> HttpResponse) {