1
1
#include < spdlog/spdlog.h>
2
-
3
2
#include < iostream>
4
3
5
4
#include " cxxopts/cxxopts.hpp"
8
7
int main (int argc, char * argv[]) {
9
8
try {
10
9
// Define the options
11
- cxxopts::Options options (" MyProgram" , " A brief description of the program " );
10
+ cxxopts::Options options (" MyProgram" , " A simple HTTP server with command-line options " );
12
11
13
- options.add_options ()(" h,help" , " Print usage information" )(" n,name" , " Name of the user" , cxxopts::value<std::string>())(" v,verbose" , " Enable verbose mode" );
12
+ // Add command-line options
13
+ options.add_options ()
14
+ (" h,help" , " Print usage information" )
15
+ (" m,mode" , " Server mode" , cxxopts::value<std::string>()->default_value (" " ))
16
+ (" n,name" , " Name of the user" , cxxopts::value<std::string>())
17
+ (" v,verbose" , " Enable verbose mode" )
18
+ (" p,port" , " Server port" , cxxopts::value<int >()->default_value (" 8080" ));
14
19
15
20
// Parse the arguments
16
21
auto result = options.parse (argc, argv);
17
22
18
23
// Handle help option
19
24
if (result.count (" help" )) {
20
- spdlog::info ( options.help ()) ;
25
+ std::cout << options.help () << std::endl ;
21
26
return 0 ;
22
27
}
23
28
@@ -35,16 +40,36 @@ int main(int argc, char* argv[]) {
35
40
spdlog::debug (" Verbose mode is enabled." );
36
41
}
37
42
38
- // Start a simple server using cpp-httplib
39
- httplib::Server svr;
43
+ // Check if server mode is specified
44
+ std::string mode = result[" mode" ].as <std::string>();
45
+ if (mode == " server" ) {
46
+ // Get port from command-line or use default
47
+ int port = result[" port" ].as <int >();
48
+
49
+ // Start a simple server using cpp-httplib
50
+ httplib::Server svr;
40
51
41
- svr.Get (" /" , [](const httplib::Request&, httplib::Response& res) {
42
- res.set_content (" Hello, World!" , " text/plain" );
43
- spdlog::info (" Handled request at /" );
44
- });
52
+ // Root route
53
+ svr.Get (" /" , [](const httplib::Request&, httplib::Response& res) {
54
+ res.set_content (" Hello, World!" , " text/plain" );
55
+ spdlog::info (" Handled request at /" );
56
+ });
45
57
46
- spdlog::info (" Starting server on http://localhost:8080" );
47
- svr.listen (" localhost" , 8080 );
58
+ // Health check route
59
+ svr.Get (" /health" , [](const httplib::Request&, httplib::Response& res) {
60
+ res.set_content (" Server is running" , " text/plain" );
61
+ spdlog::info (" Health check performed" );
62
+ });
63
+
64
+ spdlog::info (" Starting server on http://localhost:{}" , port);
65
+ if (!svr.listen (" localhost" , port)) {
66
+ spdlog::error (" Failed to start server on port {}" , port);
67
+ return 1 ;
68
+ }
69
+ } else if (!mode.empty ()) {
70
+ spdlog::error (" Invalid mode. Use --mode server to start the HTTP server." );
71
+ return 1 ;
72
+ }
48
73
49
74
} catch (const cxxopts::exceptions::exception & e) {
50
75
spdlog::error (" Error parsing options: {}" , e.what ());
0 commit comments