Add option parsing

This commit is contained in:
Tyler Perkins 2022-04-28 20:39:39 -04:00
parent bb321f6542
commit 426fcf43c4
5 changed files with 107 additions and 9 deletions

View File

@ -6,18 +6,25 @@
#include <iostream> #include <iostream>
#include <crow.h> #include <crow.h>
#include "opt/parseopt.hpp"
#include "routes.hpp"
int main(int argc, char** argv){ int main(int argc, char** argv){
option_flags* flags = parse_options(argc, argv);
crow::SimpleApp app; crow::SimpleApp app;
CROW_ROUTE(app, "/")([](){
return "Hello World";
});
CROW_ROUTE(app, "/json")([]{ setRoutes(app);
crow::json::wvalue response({{ "message", "Hello world" }});
response["kek"] = "nay, cringe";
return response;
});
app.port(5000).run(); std::cerr << "Setting up app" << std::endl;
app.port(flags->port)
.server_name("proc_api")
.multithreaded();
delete flags;
app.run();
} }

41
src/opt/parseopt.cpp Normal file
View File

@ -0,0 +1,41 @@
///////////////////////////////////////////////////////////////////////////////
// Tyler Perkins
// 28-4-22
// parseopt implementation
//
#include "parseopt.hpp"
void help(char* progName){
std::cout << "Usage: " << progName << " [FLAGS]\n";
std::cout << "Options:\n";
std::cout << " [-p] Port to listen on\n";
std::cout << " [-h] Display this help message\n\n";
exit(1);
}
option_flags* parse_options(int argc, char** argv){
char c;
option_flags* ret = new option_flags;
ret->port = 5000;
while((c = getopt(argc, argv, optarg_string)) != -1){
switch(c){
case 'p':
std::cout << optarg << "\n";
ret->port = atoi(optarg);
break;
case '?':
std::cerr << "Unkown option: " << (char)optopt << "\n";
case 'h':
help(argv[0]);
break;
default:
abort();
}
}
return ret;
}

22
src/opt/parseopt.hpp Normal file
View File

@ -0,0 +1,22 @@
///////////////////////////////////////////////////////////////////////////////
// Tyler Perkins
// 28-4-22
// parseopt definitions
//
#pragma once
#include <getopt.h>
#include <iostream>
///////////////////////////////////////
// cli options
constexpr char optarg_string[] = "p:h";
struct option_flags {
uint16_t port;
};
void help(char*);
option_flags* parse_options(int, char**);

View File

@ -0,0 +1,17 @@
///////////////////////////////////////////////////////////////////////////////
// Tyler Perkins
// 28-4-22
// Routes implementation
//
#include "routes.hpp"
void setRoutes(crow::SimpleApp& app){
CROW_ROUTE(app, "/proc/meminfo")([]{
return "Meminfo";
});
CROW_ROUTE(app, "/mem")([]{
return "mem";
});
}

11
src/routes.hpp Normal file
View File

@ -0,0 +1,11 @@
///////////////////////////////////////////////////////////////////////////////
// Tyler Perkins
// 28-4-22
// Routes definition
//
#pragma once
#include <crow.h>
void setRoutes(crow::SimpleApp&);