/************************************************************************* * * Homework 4: Exploring continuous deployment. * * File Name: quote.cpp * Course: CPTR 245 * */ #include #include #include #include #include #include "Quotes.h" std::vector explode(const std::string &s, const char &c) { std::string buff; std::vector v; for (auto n : s) { if (n != c) { buff += n; } else if (n == c && !buff.empty()) { v.push_back(buff); buff = ""; } } if (!buff.empty()) { v.push_back(buff); } return v; } int main(int argc, char **argv) { if (argc != 2) { std::cerr << "You must provide a port to run on" << std::endl; return -1; } int port = 0; try { port = std::stoi(argv[1]); } catch (const std::invalid_argument &e) { std::cerr << "Invalid port specified" << std::endl; return -1; } if (port < 1024 || port > 65535) { std::cerr << "Port is not in allowable range" << std::endl; return -1; } httplib::Server svr; svr.Get("/", [](const httplib::Request &req, httplib::Response &res) { res.set_content("Go to /quote/# or /random to get a quote.", "text/plain"); }); svr.Get("/random", [](const httplib::Request &req, httplib::Response &res) { Quotes myQuotes(time(NULL)); Quote quote = myQuotes.getRandomQuote(); std::string output = "Today's Random Quote was submitted by " + quote.student + ".\n\n" + "\"" + quote.quote + "\"\n ~ " + quote.author + "\n"; res.set_content(output, "text/plain"); }); svr.Get(R"(/quote/([0-9]+))", [](const httplib::Request &req, httplib::Response &res) { auto urlExploded = explode(req.matches[0], '/'); auto numbers = std::vector(urlExploded.begin() + 1, urlExploded.end()); Quotes myQuotes(time(NULL)); Quote quote = myQuotes.getQuote(std::stoi(numbers[0])); std::string output = "Today's Quote was submitted by " + quote.student + ".\n\n" + "\"" + quote.quote + "\"\n ~ " + quote.author + "\n"; res.set_content(output, "text/plain"); }); svr.listen("0.0.0.0", port); return 0; }