-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
85 lines (76 loc) · 2.89 KB
/
Copy pathmain.cpp
File metadata and controls
85 lines (76 loc) · 2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#undef _WIO_DEFINED
#include <io>
#include <iostream>
#include <string>
#include <spdlog/spdlog.h>
#include <drogon/drogon.h>
using namespace drogon;
int main(int argc, char const *argv[])
{
spdlog::info("Welcome to my project!");
// `registerHandler()` adds a handler to the desired path. The handler is
// responsible for generating a HTTP response upon an HTTP request being
// sent to Drogon
app().registerHandler(
"/",
[](const HttpRequestPtr &,
std::function<void(const HttpResponsePtr &)> &&callback)
{
auto resp = HttpResponse::newHttpResponse();
resp->setBody("Hello, World!");
callback(resp);
},
{Get});
// `registerHandler()` also supports parsing and passing the path as
// parameters to the handler. Parameters are specified using {}. The text
// inside the {} does not correspond to the index of parameter passed to the
// handler (nor it has any meaning). Instead, it is only to make it easier
// for users to recognize the function of each parameter.
app().registerHandler(
"/user/{user-name}",
[](const HttpRequestPtr &,
std::function<void(const HttpResponsePtr &)> &&callback,
const std::string &name)
{
auto resp = HttpResponse::newHttpResponse();
resp->setBody("Hello, " + name + "!");
callback(resp);
},
{Get});
// You can also specify that the parameter is in the query section of the
// URL!
app().registerHandler(
"/hello?user={user-name}",
[](const HttpRequestPtr &,
std::function<void(const HttpResponsePtr &)> &&callback,
const std::string &name)
{
auto resp = HttpResponse::newHttpResponse();
resp->setBody("Hello, " + name + "!");
callback(resp);
},
{Get});
// Or, if you want to, instead of asking drogon to parse it for you. You can
// parse the request yourselves.
app().registerHandler(
"/hello_user",
[](const HttpRequestPtr &req,
std::function<void(const HttpResponsePtr &)> &&callback)
{
auto resp = HttpResponse::newHttpResponse();
auto name = req->getOptionalParameter<std::string>("user");
if (!name)
resp->setBody("Please tell me your name");
else
resp->setBody("Hello, " + name.value() + "!");
callback(resp);
},
{Get});
// Ask Drogon to listen on 127.0.0.1 port 8848. Drogon supports listening
// on multiple IP addresses by adding multiple listeners. For example, if
// you want the server also listen on 127.0.0.1 port 5555. Just add another
// line of addListener("127.0.0.1", 5555)
LOG_INFO << "Server running on 127.0.0.1:8848";
app().addListener("127.0.0.1", 8848).run();
return 0;
}