Skip to content

Instantly share code, notes, and snippets.

@yannick
Created May 31, 2016 19:57
Show Gist options
  • Select an option

  • Save yannick/634bca84d97179104482051c645b0349 to your computer and use it in GitHub Desktop.

Select an option

Save yannick/634bca84d97179104482051c645b0349 to your computer and use it in GitHub Desktop.
app.d
import vibe.core.core;
import vibe.http.server;
import vibe.http.router;
import ddb.postgres;
import asdf : serializeToJson, jsonSerializer, serializeValue;
import std.algorithm : map;
import std.array : array;
import vibe.core.connectionpool;
private PostgresDB g_pgdb;
auto connectDB() {
if (!g_pgdb) {
auto params = [
"host" : "localhost",
"database" : "ecratum",
"user" : "yannick",
"password" : ""
];
g_pgdb = new PostgresDB(params);
g_pgdb.maxConcurrency = 10;
}
return g_pgdb.lockConnection();
}
struct Company
{
int id;
string name;
}
import std.typecons;
void bench(scope HTTPServerRequest req, scope HTTPServerResponse res)
{
auto conn = connectDB();
auto cmd = scoped!PGCommand(conn, "SELECT id, name from companies LIMIT 10");
auto result = cmd.executeQuery!(Company)();
result.close();
Company[] companies = result.map!(a => cast(Company) a).array;
//more complex but faster
//auto ser = jsonSerializer(a => res.writeBody(cast(string) a));
//ser.serializeValue(companies);
//ser.flush;
//easier version
res.writeBody(companies.serializeToJson() );
}
shared static this()
{
auto router = new URLRouter;
router.get("/", &bench);
auto settings = new HTTPServerSettings;
settings.port = 8080;
listenHTTP(settings, router);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment