forked from ApacheExpress/ApacheExpress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExpressMain.swift
162 lines (121 loc) · 4.23 KB
/
ExpressMain.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
//
// Copyright (C) 2017 ZeeZide GmbH, All Rights Reserved
// Created by Helge Hess on 23/01/2017.
//
import ApacheExpress
import cows
func expressMain() {
// this is our 'high level' entry point where we can register routes and such.
console.info("Attention passengers, the ZeeZide express is leaving ...")
// Level 1: demo for a generic http.Server like callback
apache.onRequest { req, res in
guard req.url.hasPrefix("/server") else { return }
console.info("simple handler:", req)
res.writeHead(200, [ "Content-Type": "text/html" ])
try res.end("<h1>Hello World</h1>")
}
// Level 2: Lets go and Connect! Middleware based processing
do {
let app = apache.connect()
app.use { req, res, next in
guard req.url.hasPrefix("/connect") else { return }
console.info("Request is passing Connect middleware ...")
// send a common header
res.setHeader("Content-Type", "text/html; charset=utf-8")
try res.write("<h4>Connect Example</h4>")
try res.write("<p><a href='/'>Homepage</a></p>")
// Note: we do not close the request, we continue with the next middleware
try next()
}
app.use("/connect/hello") { req, res, next in
console.info("Entering Hello middleware ..")
try res.write("<h1>Hello Connect!</h1>")
try res.write("<p>This is a random cow:</p><pre>")
try res.write(vaca())
try res.write("</pre>")
try res.end()
}
}
// Level 3: After Connecting we'd like to hop into the Apache Express!
do {
let app = apache.express()
// app.use(logger("dev")) - no use in Apache
app.use(bodyParser.urlencoded())
app.use(cookieParser())
app.use("/express", session())
// app.use(serveStatic(__dirname + "/public"))
// - TODO, kinda, makes less sense with Apache
app.use { req, res, next in
guard req.url.hasPrefix("/express") else { return }
console.info("Request is passing Express middleware ...")
try next()
}
// MARK: - Express Settings
// really mustache, but we want to use .html
app.set("view engine", "html")
// MARK: - Routes
let taglines = [
"Less than Perfect.",
"Das Haus das Verrückte macht.",
"Rechargeables included",
"Sensible Server Side Swift aS a Successful Software Service Solution",
"Zoftware az a a Zervice by ZeeZide"
]
// MARK: - Session View Counter
app.use { req, _, next in
req.session["viewCount"] = req.session[int: "viewCount"] + 1
try next()
}
// MARK: - Form Handling
app.get("/express/form") { _, res, _ in
try res.render("form")
}
app.post("/express/form") { req, res, _ in
let user = req.body[string: "u"]
print("USER IS: \(user)")
let options : [ String : Any ] = [
"user" : user,
"nouser" : user.isEmpty,
"viewCount" : req.session["viewCount"] ?? 0
]
try res.render("form", options)
}
// MARK: - JSON & Cookies
app.get("/express/json") { _, res, _ in
try res.json([
[ "firstname": "Donald", "lastname": "Duck" ],
[ "firstname": "Dagobert", "lastname": "Duck" ]
])
}
app.get("/express/cookies") { req, res, _ in
// returns all cookies as JSON
try res.json(req.cookies)
}
// MARK: - Cows
app.get("/express/cows") { req, res, _ in
let cow = cows.vaca()
try res.send("<html><body><pre>\(cow)</pre></body></html>")
}
// MARK: - Main page
app.get("/express/") { req, res, _ in
let tagline = arc4random_uniform(UInt32(taglines.count))
let values : [ String : Any ] = [
"tagline" : taglines[Int(tagline)],
"viewCount" : req.session["viewCount"] ?? 0,
"cowOfTheDay" : cows.vaca()
]
try res.render("index", values)
}
}
}
// helper
#if os(Linux)
import func Glibc.rand
// Looks like todays Linux Swift doesn't have arc4random either.
// Emulate it (badly).
fileprivate func arc4random_uniform(_ v : UInt32) -> UInt32 { // sigh
return UInt32(rand() % Int32(v))
}
#else
import func Darwin.arc4random_uniform
#endif