From d7e375935e54a8d5926f545a570e1e35291accdd Mon Sep 17 00:00:00 2001
From: juntao <chenjuntao@ghzhushou.com>
Date: Sat, 4 May 2019 10:10:35 +0800
Subject: [PATCH] Add header item "Content-Length" to response when
 shareFilesFromDirectory is being used to share files

---
 CHANGELOG.md              |  1 +
 XCode/Sources/Files.swift | 12 ++++++++++--
 2 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index fbff8963..a696bd81 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,7 @@ All notable changes to this project will be documented in this file. Changes not
 
 - Fixes build errors by excluding XC(UI)Test files from regular targets [#397](https://github.com/httpswift/swifter/pull/397)) by [@ChristianSteffens](https://github.com/ChristianSteffens)
 - Fixes `HttpRequest.path` value to be parsed without query parameters [#404](https://github.com/httpswift/swifter/pull/404)) by [@mazyod](https://github.com/mazyod)
+- Fixes the issue of missing `Content-Length` header item when `shareFilesFromDirectory` is being used to share files [#406](https://github.com/httpswift/swifter/pull/406) by [@nichbar](https://github.com/nichbar)
 
 ## Changed
 - Performance: Batch reads of websocket payloads rather than reading byte-by-byte. ([#387](https://github.com/httpswift/swifter/pull/387)) by [@lynaghk](https://github.com/lynaghk)
diff --git a/XCode/Sources/Files.swift b/XCode/Sources/Files.swift
index 758c75fb..977968b5 100644
--- a/XCode/Sources/Files.swift
+++ b/XCode/Sources/Files.swift
@@ -34,10 +34,18 @@ public func shareFilesFromDirectory(_ directoryPath: String, defaults: [String]
                 }
             }
         }
-        if let file = try? (directoryPath + String.pathSeparator + fileRelativePath.value).openForReading() {
+        let filePath = directoryPath + String.pathSeparator + fileRelativePath.value
+        
+        if let file = try? filePath.openForReading() {
             let mimeType = fileRelativePath.value.mimeType()
+            var responseHeader: [String: String] = ["Content-Type": mimeType]
             
-            return .raw(200, "OK", ["Content-Type": mimeType], { writer in
+            if let attr = try? FileManager.default.attributesOfItem(atPath: filePath),
+                let fileSize = attr[FileAttributeKey.size] as? UInt64 {
+                responseHeader["Content-Length"] = String(fileSize)
+            }
+            
+            return .raw(200, "OK", responseHeader, { writer in
                 try? writer.write(file)
                 file.close()
             })