首先request和response都属于message,message主要有header和body
其中header主要就是http基本信息,如GET/POST 方法等
message本身是个template,主要有一下几个类型
namespace http = boost::beast::http;
http::request<http::empty_body> req_;
req_.version(11); // http1.1
req_.method(http::verb::get); // get method
req_.target("/"); // 一个URL host:port 后面的部分,如 http://127.0.0.1:80/abc/123 , 那么 target = /abc/123
req_.set(http::field::host, "127.0.0.1");
req_.set(http::field::user_agent,BOOST_BEAST_VERSION_STRING);
namespace http = boost::beast::http;
http::string_body::value_type body;
body = "some message";
http::response<http::string_body> res{http::status::not_found, 11};
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, "text/html");
res.body() = std::move(body);
res.prepare_payload();
namespace http = boost::beast::http;
http::file_body::value_type body;
beast::error_code ec;
body.open("path", beast::file_mode::scan, ec);
http::response<http::file_body> res{http::status::not_found, 11};
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, "text/html");
res.body() = std::move(body);
res.prepare_payload();
field主要是指http header中各种字段如content-type等
所有的field请参见beast源码中 include/boost/beast/http/field.hpp
http::request<http::string_body> req;
req.set(http::field::host, host);
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
req.set(http::field::content_type, "text/html");
req.set(http::field::accept_encoding, "gzip, deflate");
if (req.find(http::field::content_type) != req.end() )
{
// find the field
boost::string_view = req.at(http::field::content_type);
// 或者使用[]操作符
}
req.insert(http::field::content_type, "text/html");
req.erase(http::field::content_type);
req.clear();
Github代码
请在listen.cpp的67行修改自己http的root文件夹目录