-
Notifications
You must be signed in to change notification settings - Fork 0
/
SwiftyWeb.swift
88 lines (71 loc) · 2.06 KB
/
SwiftyWeb.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import Foundation
/// Environment variables.
public let env = ProcessInfo.processInfo.environment
/// POST query readed with `readPost()`.
public var postString: String?
/// If POST query was readed with `readPost()`.
public var readedPost = false
/// An enumeration of HTTP methods supported by SwiftyWeb.
public enum Method {
/// Post method.
case POST
/// Get method.
case GET
}
/// Process GET or POST query into a dictionary.
///
/// - Parameters:
/// - query: Query string to process. For example: "foo=bar&bar=foo".
///
/// - Returns:
/// - Processed dictionary.
public func process(query: String) -> [String:String] {
let items = query.components(separatedBy: "&")
var dict = [String:String]()
for item in items {
let components = item.components(separatedBy:"=")
if components.count == 2 {
dict[components[0].removingPercentEncoding!.replacingOccurrences(of:"+", with: " ")] = components[1].removingPercentEncoding!.replacingOccurrences(of:"+", with: " ")
} else {
dict[components[0].removingPercentEncoding!.replacingOccurrences(of:"+", with: " ")] = ""
}
}
return dict
}
/// Read POST query if there is one.
public func readPost() {
readedPost = true
guard let length_ = env["CONTENT_LENGTH"] else { return }
if let length = Int(length_) {
if length > 0 {
postString = readLine()
}
}
}
/// Returns parsed GET query.
public var GET: [String:String] {
guard let query = env["QUERY_STRING"] else { return [:] }
return process(query: query)
}
/// Reads POST query and returns parsed query.
public var POST: [String:String] {
if !readedPost {
readPost()
}
return process(query: postString ?? "")
}
/// Returns `true` if given key is set for query for given method.
///
/// - Parameters:
/// - key: Key to check.
/// - method: Method of query where search `key`.
public func isKey(_ key: String, setForMethod method: Method) -> Bool {
var dict: [String:String] {
if method == .POST {
return POST
} else {
return GET
}
}
return dict.keys.contains(key)
}