-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathSWSGIUtils.swift
59 lines (54 loc) · 1.84 KB
/
SWSGIUtils.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//
// SWSGIUtils.swift
// Embassy
//
// Created by Fang-Pen Lin on 5/23/16.
// Copyright © 2016 Fang-Pen Lin. All rights reserved.
//
import Foundation
// from http://stackoverflow.com/a/24052094/25077
/// Update one dictionay by another
private func += <K, V>(left: inout [K: V], right: [K: V]) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
public struct SWSGIUtils {
/// Transform given request into environ dictionary
static func environFor(request: HTTPRequest) -> [String: Any] {
var environ: [String: Any] = [
"REQUEST_METHOD": String(describing: request.method),
"SCRIPT_NAME": ""
]
let queryParts = request.path.components(separatedBy: "?")
if queryParts.count > 1 {
environ["PATH_INFO"] = queryParts[0]
environ["QUERY_STRING"] = queryParts[1..<queryParts.count].joined(separator: "?")
} else {
environ["PATH_INFO"] = request.path
}
if let contentType = request.headers["Content-Type"] {
environ["CONTENT_TYPE"] = contentType
}
if let contentLength = request.headers["Content-Length"] {
environ["CONTENT_LENGTH"] = contentLength
}
environ += environFor(headers: request.headers)
return environ
}
/// Transform given header key value pair array into environ style header map,
/// like from Content-Length to HTTP_CONTENT_LENGTH
static func environFor(
headers: MultiDictionary<String, String, LowercaseKeyTransform>
) -> [String: Any] {
var environ: [String: Any] = [:]
for (key, value) in headers {
let key = "HTTP_" + key.uppercased().replacingOccurrences(
of: "-",
with: "_"
)
environ[key] = value
}
return environ
}
}