#include "crow.h" extern "C" { #include "ternarytrie.h" } #define ENV(var, env_var) \ const char *_##var = getenv(env_var); \ if (_##var == NULL) { \ printf("Missing environment variable %s.\n", env_var); \ return 1; \ } \ const std::string var = std::string(_##var); #define AUTH() \ std::string provided_api_key = req.get_header_value("X-Api-Key"); \ if (api_key.compare(provided_api_key) != 0) { \ return crow::response(crow::status::UNAUTHORIZED); \ } int main() { // Initialize random seed for generating URLs srand(time(NULL)); ENV(api_key, "LANDER_API_KEY"); ENV(base_url, "LANDER_BASE_URL"); TernaryTrie *trie = ternarytrie_init(); std::string file_path = "lander.data"; std::cout << "Populating trie from file '" << file_path << "'..." << std::endl; int count = ternarytrie_populate(trie, file_path.c_str()); if (count == -1) { std::cout << "An error occured while populating the trie." << std::endl; exit(1); } else { std::cout << "Added " << count << " entries to trie." << std::endl; } crow::SimpleApp app; app.loglevel(crow::LogLevel::Warning); CROW_ROUTE(app, "/") .methods(crow::HTTPMethod::Get)( [trie](crow::response &res, std::string s) { Entry *entry = ternarytrie_search(trie, s.c_str()); // TODO check entry type if (entry != NULL) { res.redirect(entry->string); } else { res.code = 404; } res.end(); }); CROW_ROUTE(app, "/").methods(crow::HTTPMethod::Post)( [api_key, base_url, trie](const crow::request req) { AUTH(); Entry *new_entry = entry_new(Redirect, req.body.c_str()); char *key = ternarytrie_add_random(trie, new_entry); if (key == NULL) { return crow::response(crow::status::INTERNAL_SERVER_ERROR); } std::string res = base_url + key; free(key); return crow::response(res); }); CROW_ROUTE(app, "/") .methods(crow::HTTPMethod::Post)( [api_key, base_url, trie](const crow::request &req, std::string key) { AUTH(); Entry *new_entry = entry_new(Redirect, req.body.c_str()); bool added = ternarytrie_add(trie, key.c_str(), new_entry); if (!added) { return crow::response(crow::status::CONFLICT); } return crow::response(base_url + key); }); app.port(18080).multithreaded().run(); }