- 本篇主要实现Util类,里面有多个其他类会用到的共同方法
- 废话不多说,直接上代码~
struct Util
{static int ReadLine(int sock, std::string &out){char ch = 'K';while(ch != '\n'){ssize_t s = recv(sock, &ch, 1, 0);if(s > 0){if(ch == '\r'){recv(sock, &ch, 1, MSG_PEEK); if(ch == '\n'){recv(sock, &ch, 1, 0);}else{ch = '\n';}}out.push_back(ch);}else if(s == 0){return 0;}else{return -1;}}return out.size();}static bool CutString(const std::string& str, std::string& sub1, std::string& sub2, std::string sep){size_t pos = str.find(sep);if(pos != std::string::npos){sub1 = str.substr(0, pos);sub2 = str.substr(pos + sep.size());return true;}return false;}static std::string Code2Desc(int code){std::string desc = "";switch (code){case 200:desc = "OK";break;case 404:desc = "NOT_FOUND";break;case 400:desc = "BAD_REQUEST";break;case 500:desc = "SERVER_ERROR";break;default:break;}return desc;}static std::string Suffix2Desc(const std::string& suffix){static std::unordered_map<std::string, std::string> suffix2desc = {{".html", "text/html"},{".css", "text/css"},{".js", "application/javascript"},{".jpg", "application/x-jpg"},{".xml", "application/xml"}};auto iter = suffix2desc.find(suffix);if(iter != suffix2desc.end()){return iter->second;}else{return "text/html";}}
};