File: http-server-3.cpp

package info (click to toggle)
libzeep 7.3.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,372 kB
  • sloc: cpp: 17,430; javascript: 180; makefile: 12; sh: 11
file content (67 lines) | stat: -rw-r--r-- 1,790 bytes parent folder | download
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
//         Copyright Maarten L. Hekkelman, 2025-2026
//  Distributed under the Boost Software License, Version 1.0.
//     (See accompanying file LICENSE_1_0.txt or copy at
//           http://www.boost.org/LICENSE_1_0.txt)

// In this example we don't want to use rsrc based templates
#undef WEBAPP_USES_RESOURCES
#define WEBAPP_USES_RESOURCES 0

//[ simple_http_server_3

#include <zeep/http/html-controller.hpp>
#include <zeep/http/reply.hpp>
#include <zeep/http/scope.hpp>
#include <zeep/http/server.hpp>
#include <zeep/http/template-processor.hpp>

#include <exception>
#include <filesystem>
#include <iostream>
#include <optional>
#include <string>

class hello_controller : public zeep::http::html_controller
{
  public:
	hello_controller()
	{
		/* Mount the handler `handle_index`, this is on `/` (i.e. the root) */
		map_get("", &hello_controller::handle_index, "name");

		/* Mount the handler on =/index.html= as well */
		map_get("index.html", &hello_controller::handle_index, "name");

		/* And mount the handler on a path containing the 'name' */
		map_get("hello/{name}", &hello_controller::handle_index, "name");
	}

	zeep::http::reply handle_index(const zeep::http::scope &scope, const std::optional<std::string> &user)
	{
		zeep::http::scope sub(scope);
		sub.put("name", user.value_or("world"));

		return get_template_processor().create_reply_from_template("hello.xhtml", sub);
	}
};

int main()
{
	try
	{
		/* Use the server constructor that takes the path to a docroot so it will construct a template processor */
		zeep::http::server srv(std::filesystem::canonical("docroot").string());

		srv.add_controller(new hello_controller());

		srv.bind("::", 8080);
		srv.run(2);
	}
	catch (const std::exception &ex)
	{
		std::cerr << ex.what() << '\n';
	}

	return 0;
}
//]