Created
April 28, 2017 22:29
-
-
Save kjessup/78d2ee8f7e4bb32894d6b02a3b28ff26 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import PerfectLib | |
import PerfectHTTP | |
import PerfectHTTPServer | |
let host1Routes = Routes([ | |
Route(uri: "/") { _, resp in resp.appendBody(string: "host 1").completed() } | |
]) | |
let host2Routes = Routes([ | |
Route(uri: "/") { _, resp in resp.appendBody(string: "host 2").completed() } | |
]) | |
let virtualHosts: [String:Routes] = [ | |
"127.0.0.1":host1Routes, | |
"localhost":host2Routes, | |
] | |
// An example request handler. | |
func vhostDispatch(request: HTTPRequest, response: HTTPResponse) { | |
guard let fullHost = request.header(.host), | |
let hostName = fullHost.characters.split(separator: ":").map(String.init).first else { | |
return // some sort of default handling | |
} | |
guard let virtualHost = virtualHosts[hostName.lowercased()] else { | |
return // some sort of error handling | |
} | |
guard let handler = virtualHost.navigator.findHandler(uri: request.uri, webRequest: request) else { | |
return // 404 or some such | |
} | |
handler(request, response) | |
} | |
let port1 = 8080 | |
do { | |
try HTTPServer.launch(name: "myserver", port: port1, routes: [Route(uri: "/**", handler: vhostDispatch)]) | |
} catch { | |
fatalError("\(error)") // fatal error launching one of the servers | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment