Last active
August 5, 2017 23:22
-
-
Save MainasuK/9b9bfdb7229bc5be86daad140405bcb0 to your computer and use it in GitHub Desktop.
Routes.swift demo: http://165.227.31.218:8080/fortune
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 Vapor | |
import Glibc | |
extension Droplet { | |
func setupRoutes() throws { | |
get("hello") { req in | |
var json = JSON() | |
try json.set("hello", "world") | |
return json | |
} | |
get("plaintext") { req in | |
return "Hello, world!" | |
} | |
// response to requests to /info domain | |
// with a description of the request | |
get("info") { req in | |
return req.description | |
} | |
get("description") { req in return req.description } | |
get("fortune") { _ in | |
let result = try self.exec("fortune").reduce("", { $0.appending($1) }) | |
return result | |
} | |
try resource("posts", PostController.self) | |
} | |
func exec(_ cmd: String) throws -> [String] { | |
var output = [String]() | |
let fp = popen(cmd, "r") | |
guard fp != nil else { | |
throw Abort(.internalServerError) | |
} | |
var buf = Array<CChar>(repeating: 0, count: 128) | |
while fgets(&buf, CInt(buf.count), fp) != nil { | |
output.append(String(cString: buf)) | |
} | |
pclose(fp) | |
return output | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment