Menu

[r224]: / trunk / libs / network / example / dispatch_table.cpp  Maximize  Restore  History

Download this file

82 lines (62 with data), 2.4 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
// Copyright Divye Kapoor 2008.
// 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)
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/network/protocol/http.hpp>
#include <string>
#include <map>
#include <exception>
#include <iostream>
using namespace boost::network;
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
namespace boost { namespace network { namespace http {
std::map<std::string,
http::response const (http::client::*)(http::request const &)> dispatch_table;
namespace impl {
struct init_dispatch_table {
init_dispatch_table() {
http::dispatch_table["GET"] = &http::client::get;
http::dispatch_table["POST"] = &http::client::post;
http::dispatch_table["HEAD"] = &http::client::head;
http::dispatch_table["PUT"] = &http::client::put;
http::dispatch_table["DELETE"] = &http::client::delete_;
}
};
struct unsupported_method_exception : public std::logic_error {
unsupported_method_exception(std::string const &method) :
std::logic_error( (std::string("Method ") + method + std::string(" is not a valid HTTP method.")).c_str() ) {
}
};
} // namespace impl
typedef impl::unsupported_method_exception unsupported_method;
http::response perform(http::client & client_, std::string method, http::request const & request_) {
static impl::init_dispatch_table dummy;
boost::to_upper(method);
if (http::dispatch_table.find(method) == http::dispatch_table.end())
throw http::unsupported_method(method);
return (client_.*http::dispatch_table[method])(request_);
}
} // namespace http
} // namespace network
} // namespace boost
// Prerequisite: The Python Server at tests/server/cgi_server.py must be running to serve the http request
int main() {
http::request request_("http://localhost:8000/cgi-bin/requestinfo.py");
http::client client_;
http::response response_;
// Construct request object here
try {
http::perform(client_, "GET", request_);
http::perform(client_, "POST", request_);
http::perform(client_, "UnsupportedMethod", request_);
} catch(http::unsupported_method const &e) {
cerr << e.what() << endl;
} catch(boost::system::system_error const &e) {
cerr << e.what() << endl;
}
return 0;
}