アパッチモジュール

c言語とか、ほとんど解らないから勉強の為に
curlrssを取得してきて、出力してみるアパッチモジュールを書いてみた。

#include <stdio.h>
#include "curl/curl.h"
#include "httpd.h"
#include "http_config.h"
#include "http_protocol.h"
#include "ap_config.h"
#include "http_log.h"

static void log_debug(char *message, request_rec *r)
{
    ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, "orz-log:[%s]", message);
}

/**
 *main
 */
static void orz_main(request_rec *r)
{
    log_debug("start",r);

    char error[256];

    FILE *tmp = tmpfile();
    CURL *curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &error);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, tmp);
    curl_easy_setopt(curl, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/40147582.rss");

    CURLcode res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        fprintf(stderr, error);
        goto leave;
    }
    rewind(tmp);

    log_debug("curl ok!",r);

    char s[255];
    while (fgets(s, 255, tmp) != NULL)
    {
        ap_rputs(s, r);
    }
    fclose(tmp);

leave:
    curl_easy_cleanup(curl);

    log_debug("end",r);
}

/* The sample content handler */
static int orz_handler(request_rec *r)
{
    if (strcmp(r->handler, "orz")) {
        return DECLINED;
    }
    r->content_type = "text/html";
    if (r->header_only)
    {
        log_debug("header_only", r);
        return OK;
    }
    log_debug("main start", r);
    orz_main(r);
    log_debug("main end  ", r);

    return OK;
}

/*hooks*/
static void orz_register_hooks(apr_pool_t *p)
{
    ap_hook_handler(orz_handler, NULL, NULL, APR_HOOK_MIDDLE);
}

/* Dispatch list for API hooks */
module AP_MODULE_DECLARE_DATA orz_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       */
    orz_register_hooks  /* register hooks                      */
};