在Linux下编译安装libevhtp
libevhtp 是 libevent 的 HTTP API 的另一个灵活的实现,使用 libevhtp 可以很容易地实现一个REST接口。
libevhtp网址:https://github.com/ellzey/libevhtp
这篇文章详细介绍了使用libevhtp在Linux系统下的编译和安装过程(包括SSL的安装),这篇文章使用的 libevhtp版本是1.2.11n,版本不同安装方法可能略有差异。
安装依赖
- gcc
- Libevent2
- OpenSSL(可选,forSSL)
- pthreads(可选,for多线程)
编译SSL
如果想要添加对SSL的支持,则需要先编译安装OpenSSL。构建SSL时“.config”参数至关重要,编译了很多次,尝试了很多参数,但是在构建libevent时总提示"... SSL_new not found...",说明没找到SSL模块。最后在openssl官网找到了参数。
本例使用的openssl版本是1.0.2f,编译方法如下:
tar xzvf openssl-1.0.2f.tar.gz
cd openssl-1.0.2f
./config --prefix=/usr \
--openssldir=/etc/ssl \
--libdir=lib \
shared
make
make install
编译libevent
编译libevent的方法如下,执行“make”命令之前一定要确认“./configure”的输出的配置是否正确:
./configure
make
make verify # (optional)
sudo make install
编译libevhtp
编译libevhtp可以使用下面的方法:
cd build
cmake ..
make
make install
或
cd build
cmake -DCMAKE_PREFIX_PATH=/opt/libevent -DCMAKE_INSTALL_PREFIX=/usr/local ..
make
make install
DCMAKE_PREFIX_PATH指定libevent的路径,DCMAKE_INSTALL_PREFIX指定libevhtp的安装路径。
libevhtp的使用
当使用ssl时,可能出现如下错误:
$ gcc -o main main.c -levent -levhtp -lpthread -lssl -lcrypto
//usr/local/lib/libevhtp.a(evhtp.c.o): In function `_evhtp_connection_accept':
evhtp.c:(.text+0x8d7): undefined reference to `bufferevent_openssl_socket_new'
collect2: error: ld returned 1 exit status
使用下面的配置可以解决:
$ gcc -o main main.c -levent -levhtp -lpthread -lssl -lcrypto -levent_openssl
下面是使用libevhtp搭建的一个简单的http服务器:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>
#include <evhtp.h>
void testcb(evhtp_request_t *req, void *a)
{
const char *str = a;
evbuffer_add_printf(req->buffer_out, "%s", str);
evhtp_send_reply(req, EVHTP_RES_OK);
}
int main(int argc, char **argv)
{
evbase_t *evbase = event_base_new();
evhtp_t *htp = evhtp_new(evbase, NULL);
evhtp_set_cb(htp, "/simple/", testcb, "simple");
evhtp_set_cb(htp, "/1/ping", testcb, "one");
evhtp_set_cb(htp, "/1/ping.json", testcb, "two");
#ifndef EVHTP_DISABLE_EVTHR
evhtp_use_threads(htp, NULL, 4, NULL);
#endif
evhtp_bind_socket(htp, "0.0.0.0", 8081, 1024);
event_base_loop(evbase, 0);
evhtp_unbind_socket(htp);
evhtp_free(htp);
event_base_free(evbase);
return 0;
}
推荐一个libevhtp教程:http://wiki.pchero21.com/wiki/Libevhtp
Centos安装Libevhtp: http://wiki.hourui.de/linux/centos/libevhtp
[…] Linux系统下的安装方法请参看:在Linux下编译安装libevhtp。 […]