前回の記事では、trusterdのHTTP/2サーバ機能をCアプリに組み込む方法を紹介しました。
C言語のアプリにmruby経由でtrusterdのHTTP/2サーバ機能を5分で組み込む方法 - 人間とウェブの未来
本記事では、HTTP/2クライアント機能を組み込んでみましょう。
mrubyとmruby-http2のビルド及びMakefile作成
これらは、前回の記事と同様ですので前回記事を御覧ください。
前回記事と同様の手順によって、以下のようなMakefileを作ります。
TARGET2=mini_trusterd_client.c BIN_NAME2=mini-trusterd-client MRUBY_ROOT=../mruby/ LIBMRUBY=$(MRUBY_ROOT)/build/host/lib/libmruby.a MRUBY_CFLAGS=$(shell $(MRUBY_ROOT)/bin/mruby-config --cflags) MRUBY_LDFLAGS=$(shell $(MRUBY_ROOT)/bin/mruby-config --ldflags) MRUBY_LDFLAGS_BEFORE_LIBS=$(shell $(MRUBY_ROOT)/bin/mruby-config --ldflags-before-libs) MRUBY_LIBS=$(shell $(MRUBY_ROOT)/bin/mruby-config --libs) all: gcc $(MRUBY_CFLAGS) $(MRUBY_LDFLAGS) $(TARGET2) $(LIBMRUBY) $(MRUBY_LDFLAGS_BEFORE_LIBS) $(MRUBY_LIBS) -o $(BIN_NAME2)
CアプリにHTTP/2クライアント機能を組み込む
続いてCアプリにtrusterdのHTTP/2クライアント機能を組み込んでみましょう。 例えば以下のように書くことができます。あくまで簡単なサンプルなので、自身で色々実装してみてください。
#include <stdio.h> #include "mruby.h" #include "mruby/compile.h" #include "mruby/variable.h" const char request[] = "HTTP2::Client.get @url"; int main(void) { mrb_value response; mrb_state *mrb = mrb_open(); mrbc_context *ctx = mrbc_context_new(mrb); // URL into instance variable "@url" of main on same ctx mrb_iv_set(mrb, mrb_top_self(mrb), mrb_intern_lit(mrb, "@url"), mrb_str_new_lit(mrb, "https://127.0.0.1:8080/index.html")); response = mrb_load_string_cxt(mrb, request, ctx); mrb_funcall(mrb, mrb_top_self(mrb), "pp", 1, response); mrbc_context_free(mrb, ctx); mrb_close(mrb); return 0; }
これをmakeコマンドによりビルドすると、mini-trusterd-clientというバイナリが生成されるはずです。
このmini-trusterd-clientを実行すると、
$ ./mini-trusterd-client
#<HTTP2::Response:0x1c1ce70
@response=
{stream_id>=>1,
request_headers>=>
{":method"=>"GET",
":path"=>"/index.html",
":scheme"=>"https",
":authority"=>"127.0.0.1:8080",
"accept"=>"*/*",
"accept-encoding"=>"gzip",
"user-agent"=>"mruby-http2/0.0.1"},
response_headers>=>
{":status"=>"200",
"server"=>"Trusterd/0.0.1",
"date"=>"Thu, 12 Feb 2015 15:43:33 GMT",
"content-length"=>"22",
"last-modified"=>"Sat, 27 Dec 2014 09:26:39 GMT"},
recieve_bytes>=>22.0,
body>=>"hello trusterd world.\n",
body_length>=>22,
frame_send_header_goway>=>true}>
わーい、HTTP/2クライアントでリクエストを投げてレスポンスを得られました。
HTTP/2のサーバサンプルは、下記の前回の記事で実装したうえでテストしてみるのが良いと思います。
C言語のアプリにmruby経由でtrusterdのHTTP/2サーバ機能を5分で組み込む方法 - 人間とウェブの未来
まとめ
今回の記事と前回の記事に関連して、trusterdリポジトリにC言語で書いたHTTP/2サーバとクライアントの組み込むサンプルを追加しておきました。
trusterd/src at master · trusterd/trusterd · GitHub
是非ご利用下さい。