Hello World on Silicon-HTTPリクエストで
http:// host / hello / world「hello world」というテキストを含むコード200で応答します。
auto my_api = http_api(GET / _hello / _world = [] () { return "hello world";}); mhd_json_serve(my_api, 80);
悪くないよね? ここで、my_apiはAPIの説明で、mhd_json_serveは、組み込みWebサーバー( microhttpdまたはLWANを選択)を使用してこのAPIを実装するシリコンフレームワークのバックエンドです。
シリコンが他にできることを見てみましょう。
JSONを返す
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)))
タイ層
WebAPIを作成する場合、データベースへのアクセスが必要になる可能性が高くなります。 シリコンでは、次のようになります。
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);
MySQLとSqliteがサポートされています。
間違い
HTTPプロトコルエラーコードを返すには、次の例外が使用されます。
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);
作成されたWebAPIのテスト
すべてのメソッドがテストされていない場合、WebAPIはほとんど役に立ちません。 幸いなことに、Siliconでは、APIのメソッドを呼び出すための既製の関数を使用して、説明したAPIに基づいてlibcurl_json_clientに基づくクライアントを取得できます。 テストと実際のクライアントの両方で使用できます。
// 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");