aboutsummaryrefslogtreecommitdiffstats
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rw-r--r--examples/CMakeLists.txt22
-rw-r--r--examples/example.cpp77
-rw-r--r--examples/example.py19
-rw-r--r--examples/example_chat.cpp92
-rw-r--r--examples/example_chat.html54
-rw-r--r--examples/example_test.py28
6 files changed, 292 insertions, 0 deletions
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
new file mode 100644
index 0000000..031cc04
--- /dev/null
+++ b/examples/CMakeLists.txt
@@ -0,0 +1,22 @@
+cmake_minimum_required(VERSION 2.8)
+project (crow_examples)
+
+add_executable(example example.cpp)
+#target_link_libraries(example crow)
+target_link_libraries(example ${Boost_LIBRARIES} )
+add_custom_command(OUTPUT example_test.py
+ COMMAND ${CMAKE_COMMAND} -E
+ copy ${PROJECT_SOURCE_DIR}/example_test.py ${CMAKE_CURRENT_BINARY_DIR}/example_test.py
+ DEPENDS ${PROJECT_SOURCE_DIR}/example_test.py
+ )
+add_custom_target(example_copy ALL DEPENDS example_test.py)
+
+add_executable(example_chat example_chat.cpp)
+#target_link_libraries(example_chat crow)
+target_link_libraries(example_chat ${Boost_LIBRARIES} )
+add_custom_command(OUTPUT example_chat.html
+ COMMAND ${CMAKE_COMMAND} -E
+ copy ${PROJECT_SOURCE_DIR}/example_chat.html ${CMAKE_CURRENT_BINARY_DIR}/example_chat.html
+ DEPENDS ${PROJECT_SOURCE_DIR}/example_chat.html
+ )
+add_custom_target(example_chat_copy ALL DEPENDS example_chat.html)
diff --git a/examples/example.cpp b/examples/example.cpp
new file mode 100644
index 0000000..f21a7d6
--- /dev/null
+++ b/examples/example.cpp
@@ -0,0 +1,77 @@
+#include "crow.h"
+#include "json.h"
+
+#include <sstream>
+
+class ExampleLogHandler : public crow::ILogHandler {
+ public:
+ void log(string message, crow::LogLevel level) override {
+ cerr << "ExampleLogHandler -> " << message;
+ }
+};
+
+int main()
+{
+ crow::Crow app;
+
+ CROW_ROUTE(app, "/")
+ .name("hello")
+ ([]{
+ return "Hello World!";
+ });
+
+ CROW_ROUTE(app, "/about")
+ ([](){
+ return "About Crow example.";
+ });
+
+ // simple json response
+ CROW_ROUTE(app, "/json")
+ ([]{
+ crow::json::wvalue x;
+ x["message"] = "Hello, World!";
+ return x;
+ });
+
+ 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());
+ });
+
+ CROW_ROUTE(app,"/add/<int>/<int>")
+ ([](const crow::request& req, crow::response& res, int a, int b){
+ std::ostringstream os;
+ os << a+b;
+ res.write(os.str());
+ res.end();
+ });
+
+ // 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
+ CROW_ROUTE(app, "/add_json")
+ ([](const crow::request& req){
+ auto x = crow::json::load(req.body);
+ if (!x)
+ return crow::response(400);
+ int sum = x["a"].i()+x["b"].i();
+ std::ostringstream os;
+ os << sum;
+ return crow::response{os.str()};
+ });
+
+ //crow::logger::setLogLevel(LogLevel::INFO);
+ //crow::logger::setHandler(std::make_shared<ExampleLogHandler>());
+
+ app.port(18080)
+ .multithreaded()
+ .run();
+}
diff --git a/examples/example.py b/examples/example.py
new file mode 100644
index 0000000..1fd8fcd
--- /dev/null
+++ b/examples/example.py
@@ -0,0 +1,19 @@
+from flask import Flask
+app = Flask(__name__)
+
+@app.route("/")
+def hello():
+ return "Hello World!"
+
+@app.route("/about/<path:path>/hello")
+def hello1(path):
+ return "about1"
+
+@app.route("/about")
+def hello2():
+ return "about2"
+
+print app.url_map
+
+if __name__ == "__main__":
+ app.run(host="0.0.0.0", port=8888)
diff --git a/examples/example_chat.cpp b/examples/example_chat.cpp
new file mode 100644
index 0000000..b12926a
--- /dev/null
+++ b/examples/example_chat.cpp
@@ -0,0 +1,92 @@
+#include "crow.h"
+#include "json.h"
+#include "mustache.h"
+#include <string>
+#include <vector>
+#include <chrono>
+
+using namespace std;
+
+vector<string> msgs;
+vector<pair<crow::response*, decltype(chrono::steady_clock::now())>> ress;
+
+void broadcast(const string& msg)
+{
+ msgs.push_back(msg);
+ crow::json::wvalue x;
+ x["msgs"][0] = msgs.back();
+ x["last"] = msgs.size();
+ string body = crow::json::dump(x);
+ for(auto p:ress)
+ {
+ auto* res = p.first;
+ CROW_LOG_DEBUG << res << " replied: " << body;
+ res->end(body);
+ }
+ ress.clear();
+}
+
+int main()
+{
+ crow::App app;
+ crow::mustache::set_base(".");
+
+ CROW_ROUTE(app, "/")
+ ([]{
+ crow::mustache::context ctx;
+ return crow::mustache::load("example_chat.html").render();
+ });
+
+ CROW_ROUTE(app, "/logs")
+ ([]{
+ CROW_LOG_INFO << "logs requested";
+ crow::json::wvalue x;
+ int start = max(0, (int)msgs.size()-100);
+ for(int i = start; i < (int)msgs.size(); i++)
+ x["msgs"][i-start] = msgs[i];
+ x["last"] = msgs.size();
+ CROW_LOG_INFO << "logs completed";
+ return x;
+ });
+
+ CROW_ROUTE(app, "/logs/<int>")
+ ([](const crow::request& req, crow::response& res, int after){
+ CROW_LOG_INFO << "logs with last " << after;
+ if (after < (int)msgs.size())
+ {
+ crow::json::wvalue x;
+ for(int i = after; i < (int)msgs.size(); i ++)
+ x["msgs"][i-after] = msgs[i];
+ x["last"] = msgs.size();
+
+ res.write(crow::json::dump(x));
+ res.end();
+ }
+ else
+ {
+ vector<pair<crow::response*, decltype(chrono::steady_clock::now())>> filtered;
+ for(auto p : ress)
+ {
+ if (p.first->is_alive() && chrono::steady_clock::now() - p.second < chrono::seconds(30))
+ filtered.push_back(p);
+ else
+ p.first->end();
+ }
+ ress.swap(filtered);
+ ress.push_back({&res, chrono::steady_clock::now()});
+ CROW_LOG_DEBUG << &res << " stored " << ress.size();
+ }
+ });
+
+ CROW_ROUTE(app, "/send")
+ ([](const crow::request& req)
+ {
+ CROW_LOG_INFO << "msg from client: " << req.body;
+ broadcast(req.body);
+ return "";
+ });
+
+ app.port(40080)
+ //.multithreaded()
+ .run();
+}
diff --git a/examples/example_chat.html b/examples/example_chat.html
new file mode 100644
index 0000000..233e093
--- /dev/null
+++ b/examples/example_chat.html
@@ -0,0 +1,54 @@
+<html>
+<head>
+<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
+</head>
+<body>
+<input id="msg" type="text">
+<button id="send">Send</button>
+<div id="logs">
+</div>
+<script>
+$(document).ready(function(){
+ $("#send").click(function(){
+ var msg = $("#msg").val();
+ console.log(msg);
+ if (msg.length > 0)
+ $.post("/send", msg);
+ $("#msg").val("");
+ });
+ $("#msg").keyup(function(event){
+ if(event.keyCode == 13){
+ $("#send").click();
+ }
+ });
+ var lastLog = 0;
+ var updateLog;
+ updateLog = function(data)
+ {
+ console.log("recv ");
+ console.log(data);
+ var lastLog = data.last*1;
+ console.log("lastLog: " + lastLog);
+ var s = "";
+ function htmlEncode(s)
+ {
+ return s.replace(/&(?!\w+([;\s]|$))/g, "&amp;")
+ .replace(/</g, "&lt;").replace(/>/g, "&gt;");
+ }
+ for(var x in data.msgs)
+ {
+
+ s = htmlEncode(data.msgs[x]) + "<BR>" + s;
+ }
+ $("#logs").html(s+$("#logs").html());
+ var failFunction;
+ failFunction = function(){
+ $.getJSON("/logs/"+lastLog, updateLog).fail(failFunction);
+ };
+ $.getJSON("/logs/"+lastLog, updateLog).fail(failFunction);
+ }
+ $.getJSON("/logs", updateLog);
+});
+</script>
+</body>
+</html>
diff --git a/examples/example_test.py b/examples/example_test.py
new file mode 100644
index 0000000..e2bf651
--- /dev/null
+++ b/examples/example_test.py
@@ -0,0 +1,28 @@
+import urllib
+assert "Hello World!" == urllib.urlopen('http://localhost:18080').read()
+assert "About Crow example." == urllib.urlopen('http://localhost:18080/about').read()
+assert 404 == urllib.urlopen('http://localhost:18080/list').getcode()
+assert "3 bottles of beer!" == urllib.urlopen('http://localhost:18080/hello/3').read()
+assert "100 bottles of beer!" == urllib.urlopen('http://localhost:18080/hello/100').read()
+assert 400 == urllib.urlopen('http://localhost:18080/hello/500').getcode()
+assert "3" == urllib.urlopen('http://localhost:18080/add_json', data='{"a":1,"b":2}').read()
+assert "3" == urllib.urlopen('http://localhost:18080/add/1/2').read()
+
+# test persistent connection
+import socket
+import time
+s = socket.socket()
+s.connect(('localhost', 18080))
+for i in xrange(10):
+ s.send('''GET / HTTP/1.1
+Host: localhost\r\n\r\n''');
+ assert 'Hello World!' in s.recv(1024)
+
+# test timeout
+s = socket.socket()
+s.connect(('localhost', 18080))
+print 'ERROR REQUEST'
+s.send('''GET / HTTP/1.1
+hHhHHefhwjkefhklwejfklwejf
+''')
+print s.recv(1024)