创建http_server.cc
touch http_server.cc
http_server.cc
#include "searcher.hpp"
int main()
{
return 0;
}
makefile
PARSER=parser
DUG=debug
HTTP_SERVER=http_server
cc=g++
.PHONY:all
all:$(PARSER) $(DUG) $(HTTP_SERVER)
$(PARSER):parser.cc
$(cc) -o $@ $^ -lboost_system -lboost_filesystem -std=c++11
$(DUG):debug.cc
$(cc) -o $@ $^ -ljsoncpp -std=c++11
$(HTTP_SERVER):http_server.cc
$(cc) -o $@ $^ -ljsoncpp -std=c++11
.PHONY:clean
clean:
rm -f $(PARSER) $(DUG) $(HTTP_SERVER)
引入cpp-httplib库
地址:
GitHub - yhirose/cpp-httplib: A C++ header-only HTTP/HTTPS server and client library
这里引入0.7.15版本
直接将文件拖入
unzip cpp-httplib-0.7.15.zip
解压缩文件
将cpp-httplib引入
ln -s ./test/cpp-httplib-0.7.15 cpp-httplib
使用httplib库
makefile引入pthread库
PARSER=parser
DUG=debug
HTTP_SERVER=http_server
cc=g++
.PHONY:all
all:$(PARSER) $(DUG) $(HTTP_SERVER)
$(PARSER):parser.cc
$(cc) -o $@ $^ -lboost_system -lboost_filesystem -std=c++11
$(DUG):debug.cc
$(cc) -o $@ $^ -ljsoncpp -std=c++11
$(HTTP_SERVER):http_server.cc
$(cc) -o $@ $^ -ljsoncpp -lpthread -std=c++11
.PHONY:clean
clean:
rm -f $(PARSER) $(DUG) $(HTTP_SERVER)
http_server.cc
#include "searcher.hpp"
#include "cpp-httplib/httplib.h"
int main()
{
httplib::Server svr;
svr.Get("/hi", [](const httplib::Request &req, httplib::Response &rsp){
rsp.set_content("hello world!", "text/plain; charset=utf-8");
});
svr.listen("0.0.0.0", 8081);
return 0;
}
测试
运行http_server
netstat -ntlp
有一个8081的服务,处于listen状态
新建一个wwwroot目录
mkdir wwwroot
在wwwroot文件夹里创建一个index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>for test</title>
</head>
<body>
<h1>你好,世界</h1>
<p>这是个httplib的测试</p>
</body>
</html>
完成http调用
#include "cpp-httplib/httplib.h"
#include "searcher.hpp"
const std::string input = "data/raw_html/raw.txt";
const std::string root_path = "./wwwroot";
int main()
{
ns_searcher::Searcher search;
search.InitSearcher(input);
httplib::Server svr;
svr.set_base_dir(root_path.c_str());
svr.Get("/s", [&search](const httplib::Request &req, httplib::Response &rsp){
if(!req.has_param("word")){
rsp.set_content("必须要有搜索关键字!", "text/plain; charset=utf-8");
return;
}
std::string word = req.get_param_value("word");
std::cout << "用户在搜索:" << word << std::endl;
std::string json_string;
search.Search(word, &json_string);
rsp.set_content(json_string, "application/json");
//rsp.set_content("你好,世界!", "text/plain; charset=utf-8");
});
svr.listen("0.0.0.0", 8081);
return 0;
}