#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //for getopt, fork
#include <string.h> //for strcat
#include <sys/queue.h>
#include <event.h> //for http
#include <evhttp.h>
#include <signal.h>
void specific_handler(struct evhttp_request *req,void *arg)
{
char debug[32] = "post data from c";
//HTTP header
evhttp_add_header(req->output_headers, "Server", MYHTTPD_SIGNATURE);
evhttp_add_header(req->output_headers, "Content-Type", "text/plain; charset=UTF-8");
evhttp_add_header(req->output_headers, "Connection", "close");
//输出的内容
struct evbuffer *buf;
buf = evbuffer_new();
evbuffer_add_printf(buf, "%s", debug);
evhttp_send_reply(req, HTTP_OK, "OK", buf);
char *post_data = EVBUFFER_DATA(req->input_buffer);
evbuffer_free(buf);
}
//处理模块
void httpd_handler(struct evhttp_request *req, void *arg)
{
//HTTP header
evhttp_add_header(req->output_headers, "Server", MYHTTPD_SIGNATURE);
evhttp_add_header(req->output_headers, "Content-Type", "text/plain; charset=UTF-8");
evhttp_add_header(req->output_headers, "Connection", "close");
//输出的内容
struct evbuffer *buf;
buf = evbuffer_new();
evbuffer_add_printf(buf, "%s", data);
evhttp_send_reply(req, HTTP_OK, "OK", buf);
evbuffer_free(buf);
}
//当向进程发出SIGTERM/SIGHUP/SIGINT/SIGQUIT的时候,终止event的事件侦听循环
void signal_handler(int sig)
{
switch (sig)
{
case SIGTERM:
case SIGHUP:
case SIGQUIT:
case SIGINT:
event_loopbreak(); //终止侦听event_dispatch()的事件侦听循环,执行之后的代码
break;
}
}
int n2n_front()
{
//自定义信号处理函数
signal(SIGHUP, signal_handler);
signal(SIGTERM, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGQUIT, signal_handler);
//默认参数
char *httpd_option_listen = "127.0.0.1";
int httpd_option_port = 25536;
int httpd_option_daemon = 0;
int httpd_option_timeout = 120; //in seconds
//判断是否设置了-d,以daemon运行
if (httpd_option_daemon)
{
pid_t pid;
pid = fork();
if (pid < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid > 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid > 0) {
//生成子进程成功,退出父进程
exit(EXIT_SUCCESS);
}
}
/* 使用libevent创建HTTP Server */
//初始化event API
event_init();
//创建一个http server
struct evhttp *httpd;
httpd = evhttp_start(httpd_option_listen, httpd_option_port);
evhttp_set_timeout(httpd, httpd_option_timeout);
//也可以为特定的URI指定callback
evhttp_set_cb(httpd, "/about", specific_handler, NULL);
// evhttp_set_cb(httpd, "/zhuce", specific_handler2, NULL);
//指定generic callback
evhttp_set_gencb(httpd, httpd_handler, NULL);
//循环处理events
event_dispatch();
evhttp_free(httpd);
return 1;
}