http: // host / hello / worldwill respond with code 200 with the text “hello world”:
auto my_api = http_api(GET / _hello / _world = [] () { return "hello world";}); mhd_json_serve(my_api, 80);
GET / _hi = [] () { return D(_name = "John", _age = 42); }
POST / _hello / _id[int()] // URL- * get_parameters(_name) // GET- * post_parameters(_age = int()) // POST- = [] (auto p) // p { std::ostringstream ss; ss << p.name << p.age << p.id; return ss.str(); }
GET / _hello * get_parameters(_id = optional(int(42)))
auto my_api = http_api( GET / _username / _id[int()] = [] (auto p, mysql_connection& db) { std::string name; db("SELECT name from User where id = ?")(id) >> name; return D(_name = name); } ); auto middlewares = std::make_tuple( mysql_connection_factory("localhost", "user", "password", "database_name") ); mhd_json_serve(my_api, middlewares, 8080);
GET / _test / _id[int()] = [] (auto p) { if (p.id != 42) // 401 (Unauthorized) throw error::unauthorized("Wrong ID"); return "success"; }
struct session { int id; }; auto api = http_api( GET / _set_id / _id[int()] = [] (auto p, session& s) { s.id = p.id; }, GET / _get_id = [] (session& s) { return D(_id = s.id); } ); auto middlewares = std::make_tuple( hashmap_session_factory<session>() ); mhd_json_serve(my_api, middlewares, 8080);
// API auto my_api = http_api( POST / _hello / _world / _id[int()] * get_parameters(_name, _city) = [] (auto p) { return D(_id = p.id, _name = p.name, _city = p.city); } ); // auto server = sl::mhd_json_serve(hello_api, 8080, _non_blocking); // auto c = libcurl_json_client(my_api, "127.0.0.1", 8080); // c.http_get GET- // c.http_post POST- // c.http_put PUT- // c.http_delete DELETE- // auto r = c.http_post.hello.world(_id = 42, _name = "John", _city = "Paris"); assert(r.status == 200); assert(r.response.id == 42); assert(r.response.name == "John"); assert(r.response.city == "Paris");
Source: https://habr.com/ru/post/280214/
All Articles