-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathexample.cpp
94 lines (76 loc) · 2.43 KB
/
example.cpp
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
86
87
88
89
90
91
92
93
94
#include <sstream>
#include <string>
#include <vector>
#include "crow.h"
int main()
{
crow::SimpleApp app;
CROW_ROUTE(app, "/about")
([](){
return "About Crow example.";
});
// JSON response
// Source: https://github.com/ipkn/crow/blob/master/tests/unittest.cpp
CROW_ROUTE(app, "/json")
([]{
crow::json::wvalue x;
x["message"] = "Hello, World!";
x["numbers"]["x"] = 3;
x["numbers"]["y"] = 5;
x["scores"][0] = 1;
x["scores"][1] = "king";
x["scores"][2] = 3.5;
x["scores"][3][0] = "real";
x["scores"][3][1] = false;
x["scores"][3][2] = true;
x["tree"]["a1"]["b"]["c"] = nullptr;
x["tree"]["a2"] = std::vector<int>{1,2,3};
return x;
});
// argument
CROW_ROUTE(app,"/hello/<int>")
([](int count){
if (count > 100)
return crow::response(400);
std::ostringstream os;
os << count << " bottles of beer!";
return crow::response(os.str());
});
// Compile error with message "Handler type is mismatched with URL paramters"
//CROW_ROUTE(app,"/another/<int>")
//([](int a, int b){
//return crow::response(500);
//});
// more json example
// e.g. curl -X POST -H 'X-TEST-Header: MyGoodness' http://127.0.0.1:8080/add_json -d '{"a": 1, "b": 3, "message": "Hello!"}'
CROW_ROUTE(app, "/add_json")
.methods("POST"_method)
([](const crow::request& req){
auto x = crow::json::load(req.body);
// Get header value for X-TEST-Header
std::string header_str = req.get_header_value("X-TEST-Header");
if (!x)
return crow::response(400);
int sum = x["a"].i()+x["b"].i();
std::string message = x["message"].s();
std::ostringstream os;
os << message << " " << sum << " " << header_str;
return crow::response{os.str()};
});
// Limit to only POST and GET
// To test:-
// curl -X GET http://127.0.0.1:8080/multi_method
// curl -X POST http://127.0.0.1:8080/multi_method
CROW_ROUTE(app, "/multi_method")
.methods("POST"_method, "GET"_method)
([](const crow::request& req){
// get the METHOD name
std::string method_name = crow::method_name(req.method);
std::ostringstream os;
os << method_name;
return crow::response{os.str()};
});
app.port(8080)
.multithreaded()
.run();
}