C++一个头文件实现http服务器的搭建【cpp-httplib】

6,177 阅读2分钟

cpp-httplib简介

cpp-httplib是一个以C++11特性编写的,跨平台HTTP/HTTPS库。使用时,只需在代码中包含httplib.h文件。
注意:这是一个多线程的阻塞HTTP库。
在简易点餐系统的项目中,我使用httplib库来实现http服务器的搭建,所以我们在这里介绍一下httplib的工作流程。

下载:github.com/yhirose/cpp…

编译:

解压压缩包,可以看到所有的代码都包含在httplib.h这个头文件中,httplib本身是无须编译的。
但是对使用者来说,在linux平台,httplib要求gcc必须高于4.8,像centos7环境必须升级gcc。
在windows平台,httplib要求vs至少是2015以上,或者qt版本5.9以上。

此外,如果需要使用HTTPS,httplib还依赖openssl 1.1.1。

使用HTTP:

下面用一个简单的例子,说明在linux、vs、qt如何使用。

代码,保存为test.cpp:

**

#include <stdio.h>
#include <stdlib.h>
#include "httplib.h"

void doGetHi(const httplib::Request& req, httplib::Response& res)
{
    res.set_content("hi", "text/plain");
}

int main(int argc, char *argv[])
{
    httplib::Server server;
    server.Get("/hi", doGetHi);
    server.listen("0.0.0.0", 8081);
    return 0;
}

liunx下编译:
g++ -o test test.cpp -pthread

vs下编译:
将httplib.h拷贝到工程目录,或者配置好头文件依赖,按F7编译。

qt下编译:
将httplib.h拷贝到工程目录,或者配置好头文件和库依赖,需修改.pro工程文件,添加:
INCLUDEPATH += 包含目录
LIBS += -lWs2_32
然后编译。

使用HTTPS:

修改代码为:

**

#include <stdio.h>
#include <stdlib.h>

#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "httplib.h"

void doGetHi(const httplib::Request& req, httplib::Response& res)
{
    res.set_content("hi", "text/plain");
}

int main(int argc, char *argv[])
{
    httplib::SSLServer server("./server.crt", "./server.key");
    server.Get("/hi", doGetHi);
    server.listen("0.0.0.0", 8081);
    return 0;
}

编译,以linux举例,执行命令:
g++ -o test test.cpp -I/usr/local/openssl/include -L/usr/local/openssl/lib -lssl -lcrypto -pthread

客户端使用curl命令:
curl https://127.0.0.1:8081/hi -k
-k选项表示不要对证书进行认证。

制作自签证书:
命令如下:
openssl genrsa -out server.key 1024
openssl req -new -key server.key -out server.csr
openssl x509 -days 1024 -req -in server.csr -signkey server.key -out server.crt