使用Drogon的CSP模板生成静态页面
前言
因为博客站点的服务器的,一直是单核1G内存的配置,所以博文都是生成静态页面的,这里使用Drogon的CSP模板静态页面,使用还是很简单的.生成静态页面的代码不多.{
HttpViewData data;
data.insert("article", article); //将文章内容放入HttpViewData中
data.insert("categoryList", categoryList); //将文章类别放入HttpViewData中
auto htmlTemplate =
HttpResponse::newHttpViewResponse("HtmlTemplate", data); //使用csp模板
string htmlName;
htmlName.reserve(64);
htmlName.append(app().getDocumentRoot()); //这里为站点指定的根目录
htmlName.append("articles/");
htmlName.append(filename); //*********这里遇到点小问题
std::ofstream ow(htmlName, std::ios::binary); //
ow << htmlTemplate->getBody(); //获取csp解析后的内容,写入静态文件中,这里不考虑宽字符
}
至于代码中,为什么说不考虑宽字符?在前面有说到过. Drogon视图生成源文件乱码 ,还是比较吐槽C++的字符串很难用.
遇到的问题
说说上面遇到的问题,就是生成的静态页面的文件判断是否html后缀名.当时有点疑惑.std::string str = "123";
auto p = str.find(".html");
int pp = str.find(".html");
std::cout << "p=" << p << std::endl; // 猜猜p的值是多少?
std::cout << "pp=" << pp << std::endl; // 猜猜p的值是多少?
因为使用auto比较方便,所以在auto自动识别返回值类型,但出现的结果,让我有点意外的.这一点和C#/JavaScript的IndexOf方法不太一样,这两个语言查找不到的话,返回值为-1 .后面去string find文档,发现find返回值类型要使用的std::string::size_type.查找不到的话要和std::string::npos是否相等.
std::string str = "123";
std::string::size_type p = str.find(".html");
if (p != std::string::npos) {//字符串包含.html
std::cout << str << std::endl;
} else {
std::cout << str + ".html" << std::endl; //没有.html的,要加上文件后缀名
}
看一下npos是如何定义的:
static constexpr auto npos{static_cast<size_type>(-1)}; //npos的值还是-1
所以不使用string类型下的size_type,使用int也是可以的,只是使用npos可以更有语义,应该是no pos吧.来来文档的解释:
static const size_type npos = -1;
/* This is a special value equal to the maximum value representable by the type size_type. The exact meaning depends on context, but it is generally used either as end of string indicator by the functions that expect a string index or as the error indicator by the functions that return a string index.
*/
/* Note
Although the definition uses -1, size_type is an unsigned integer type, and the value of npos is the largest positive value it can hold, due to signed-to-unsigned implicit conversion. This is a portable way to specify the largest value of any unsigned type.
*/
这是一个特殊值,等于size_type类型所能表示的最大值。确切的含义取决于上下文,但它通常被期望字符串索引的函数用作字符串结束指示符,或被返回字符串索引的函数用作错误指示符。
请注意
虽然定义使用了-1,但size_type是一个无符号整型,npos的值是它能容纳的最大正值,这是由于有符号到无符号的隐式转换。这是一种指定任何无符号类型的最大值的可移植方法。
结果
这里顺便学习字符串的查找,其实这里使用find,并不是很合适,这里可以find_last_of,如果使用新版本的话,是可以使用starts_with和ends_with,这两个函数是返回值bool值.
秋风
2023-03-21