目录
 
  
 
 
 
0.CGI程序主要干什么?
 
- CGI数据处理主要由外部CGI程序负责,HttpServer只负责将拿到的参数交给CGI程序 
  
- 即:CGI程序既需要数据处理又需要任务处理,最后将结果传递回HttpServer
 
  - 本质上就是给一个某个功能的软件,套上了一层壳 
  
- 解析HttpServer传递的参数
 - 实现某个功能
 - 将结果传递回HttpServer
 
  
 
 
1.数据处理
 
 
bool GetQuery(std::string& out)
{
    std::string method = getenv("METHOD");
    bool ret = false;
    if (method == "GET")
    {
        out = getenv("ARG");
        ret = true;
    }
    else if (method == "POST")
    {
        
        int content_length = atoi(getenv("CLENGTH"));
        char ch = 'K';
        while (content_length--)
        {
            read(0, &ch, 1);
            out.push_back(ch);
        }
        ret = true;
    }
    else
    {
        
    }
    return ret;
}
void CutString(const std::string& in, std::string& out1, std::string& out2, const std::string sep)
{
    auto pos = in.find(sep);
    if(pos != std::string::npos)
    {
        out1 = in.substr(0, pos);
        out2 = in.substr(pos + sep.size());
    }
}
 
 
2.任务处理
 
- 将解析出来的参数,用于任务处理,处理什么任务,就需要看具体场景,写具体代码了
 - 此处以一个简易计算器为例
 
 
int main()
{
    
    std::string queryStr;
    GetQuery(queryStr);
    
    std::string arg1, arg2;
    CutString(queryStr, arg1, arg2, "&");
    std::string key1, value1, key2, value2;
    CutString(arg1, key1, value1, "=");
    CutString(arg2, key2, value2, "=");
    
    std::cout << key1 << ":" << value1 << endl;
    std::cout << key2 << ":" << value2 << endl;
    
    std::cerr << "CGI: " << key1 << ":" << value1 << endl;
    std::cerr << "CGI: " << key2 << ":" << value2 << endl;
    int x = atoi(value1.c_str());
    int y = atoi(value2.c_str());
    
    std::cout << "<html>";
    std::cout << "<head><meta charset=\"utf-8\"></head>";
    std::cout << "<body>";
    std::cout << "<h3> " << value1 << " + " << value2 << " = " << x + y << "</h3>";
    std::cout << "<h3> " << value1 << " - " << value2 << " = " << x - y << "</h3>";
    std::cout << "<h3> " << value1 << " * " << value2 << " = " << x * y << "</h3>";
    std::cout << "<h3> " << value1 << " / " << value2 << " = " << x / y << "</h3>";
    std::cout << "</body>";
    std::cout << "</html>";
    return 0;
}