Apache Module 作成 ~~HelloWorld~~
概要
社内のいろんな人がapacheやnginxのモジュールを作成してアウトプットされているので自分もこの流れにのっかって(だいぶ遅い)とりあえずApacheのモジュールを作成してみようお思ったのでブログ書いてみた。
いろいろ
- VM:Vagrant + virtualBox
- OS:CentoOS7
httpd -v Server version: Apache/2.2.15 (Unix) Server built: Feb 9 2016 17:28:49
雛形作成
apxインストール
apxという便利なコマンドを使えばモジュールの雛形が作成できるみたい。apxをインストール。
yum install httpd-devel
雛形出力
apxs -g -n hello
- -g : 雛形生成指定
- -n : モジュールの名前指定(ハイフンをつけたらコンパイルエラーになってはまった。)
結果
$ ls
Makefile mod_hello.c modules.mk
mod_hello.c
#include "httpd.h" #include "http_config.h" #include "http_protocol.h" #include "ap_config.h" /* The sample content handler */ static int hello_handler(request_rec *r) { if (strcmp(r->handler, "hello")) { return DECLINED; } r->content_type = "text/html"; if (!r->header_only) ap_rputs("The sample page from mod_hello.c\n", r); return OK; } static void hello_register_hooks(apr_pool_t *p) { ap_hook_handler(hello_handler, NULL, NULL, APR_HOOK_MIDDLE); } /* Dispatch list for API hooks */ module AP_MODULE_DECLARE_DATA hello_module = { STANDARD20_MODULE_STUFF, NULL, /* create per-dir config structures */ NULL, /* merge per-dir config structures */ NULL, /* create per-server config structures */ NULL, /* merge per-server config structures */ NULL, /* table of config file commands */ hello_register_hooks /* register hooks */ };
コンパイル&インストール
apxs -i -a -c mod_hello_world.c
インストールオプション
-c This indicates the compilation operation. It first compiles the C source files (.c) of files into corresponding object files (.o) and then builds a dynamically shared object in dsofile by linking these object files plus the remaining object files (.o and .a) of files. If no -o option is speci‐ fied the output file is guessed from the first filename in files and thus usually defaults to mod_name.so. -i This indicates the installation operation and installs one or more dynami‐ cally shared objects into the server's modules directory. -a This activates the module by automatically adding a corresponding LoadMod‐ ule line to Apache's httpd.conf configuration file, or by enabling it if it already exists.
結果(色々できてる)
ls
Makefile mod_hello.c mod_hello.la mod_hello.lo mod_hello.o mod_hello.slo modules.mk
httpd.conf
/hello/ で始まる URI のリクエストを処理するハンドラーを指定。
<Location "/hello/"> SetHandler hello </Location>
モジュールのダイナミックリンク指定
自動で追加される↓
LoadModule hello_module /usr/lib64/httpd/modules/mod_hello.so
結果
apache再起動でhtt://localhost/hello/で以下が表示される
The sample page from mod_hello.c