- 可为每种情况都确实对应一个状态码,当发生错误时,跳转到对应的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()
{_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: path += PAGE_404;HandlerError(path);break;case SERVER_ERROR:path += PAGE_404;HandlerError(path);break;default:break;}
}
void HandlerError(std::string page)
{_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; 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);}
}