您的位置:首页 > 娱乐 > 八卦 > [项目][WebServer][解析错误处理]详细讲解

[项目][WebServer][解析错误处理]详细讲解

2025/3/12 13:37:06 来源:https://blog.csdn.net/qq_37281656/article/details/142212223  浏览:    关键词:[项目][WebServer][解析错误处理]详细讲解
  • 可为每种情况都确实对应一个状态码,当发生错误时,跳转到对应的html页面即可
  • 但是为了代码的复用性,可以将所有的错误情况都归置处理
#define SEP ": "
#define LINE_END "\r\n"
#define WEB_ROOT  "wwwroot"
#define HOME_PAGE "index.html"
#define HTTP_VERSION "HTTP/1.0"
#define PAGE_404 "404.html"#define OK 200
#define BAD_REQUEST 400
#define NOT_FOUND 404
#define SERVER_ERROR 500void BuildResponseHelper()
{// 此处status_line是干净的,没有内容的// 构建状态行_response.status_line += HTTP_VERSION;_response.status_line += " ";_response.status_line += std::to_string(_response.status_code);_response.status_line += " ";_response.status_line += Util::Code2Desc(_response.status_code);_response.status_line += LINE_END;// 构建响应正文,可能包括响应报头std::string path = WEB_ROOT;path += '/';switch (_response.status_code){case OK:BuildOKResponse();break;case NOT_FOUND:path += PAGE_404;HandlerError(path);break;case BAD_REQUEST:  // 暂时先404处理,后面有需要再改path += PAGE_404;HandlerError(path);break;case SERVER_ERROR:path += PAGE_404;HandlerError(path);break;default:break;}
}// 总不能为每一种错误都单独写一个处理函数吧?
// 将所有错误情况归置处理
void HandlerError(std::string page)
{// ProcessCgi()中也可能出错,所以此时将cgi置false// 这样发送效应的时候就会按非cgi模式发送_request.cgi = false;// 给用户返回对应的错误页面_response.fd = open(page.c_str(), 0, O_RDONLY);if (_response.fd > 0){struct stat st;stat(page.c_str(), &st);_response.fSize = st.st_size; // 重置大小,否则send时按正常请求的网页大小发std::string line = "Content-Type: text/html";line += LINE_END;_response.response_header.push_back(line);line = "Content-Length: ";line += std::to_string(st.st_size);line += LINE_END;_response.response_header.push_back(line);}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com