bool http_servlet::doReply(acl::HttpServletRequest&, acl::HttpServletResponse& res, int status, const char* fmt, ...) { acl::string buf; va_list ap; va_start(ap, fmt); buf.vformat(fmt, ap); va_end(ap); res.setStatus(status); res.setContentLength(buf.size()); return res.write(buf) && res.write(NULL, 0); }
bool http_servlet::doReply(acl::HttpServletRequest& req, acl::HttpServletResponse& res, int status, acl::json& json) { res.setStatus(status); res.setContentType("text/json"); if (1) res.setKeepAlive(req.isKeepAlive()); else res.setKeepAlive(false); const acl::string& data = json.to_string(); res.setContentLength(data.size()); return res.write(data) && res.write(NULL, 0); }
bool http_servlet::doDoc(acl::HttpServletRequest& req, acl::HttpServletResponse& res, const char* path) { acl::string filepath(var_cfg_home_path); if (*(var_cfg_home_path + strlen(var_cfg_home_path) - 1) != '/' && *path != '/') { filepath << '/'; } filepath << path; if (*(path + strlen(path) - 1) == '/') filepath << "index.html"; acl::ifstream in; if (in.open_read(filepath) == false) { logger_error("open %s error %s", filepath.c_str(), acl::last_serror()); return doReply(req, res, 404, "%s", "Not found"); } //printf("---open %s ok---\r\n", filepath.c_str()); long long len = in.fsize(); if (len <= 0) { logger_error("invalid fisze: %lld, file: %s", len, filepath.c_str()); return doReply(req, res, 500, "%s", "Can't get file size"); } res.setContentLength(len); acl::string ctype; getContentType(filepath, ctype); res.setContentType(ctype); char buf[8192]; int ret; long long n = 0; while (!in.eof()) { if ((ret = in.read(buf, sizeof(buf), false)) == -1) { //logger_error("read from %s error %s", filepath.c_str(), // acl::last_serror()); break; } if (res.write(buf, ret) == false) { logger_error("write to client error, file %s", filepath.c_str()); return false; } n += ret; } if (n != len) { logger_error("write length(%lld) != file size(%lld), file: %s", n, len, filepath.c_str()); return false; } return res.write(NULL, 0); }