Deutsch

Воспоминания Си Джи Ай 15.02.2025

48  
uscheswoi_82 патриот5 дней назад, 16:10
5 дней назад, 16:10 

Всем привет! Хотел бы сегодня вспомнить CGI.

CGI (от англ. Common Gateway Interface — «Общий интерфейс шлюза») — спецификация интерфейса, используемого внешней программой для связи с веб-сервером. Последний вариант описан в RFC 3875. Шлюзом тут является веб-сервер, который получает запрос от клиента, преобразует в CGI-форму, вызывает обработчик и конвертирует его ответ из CGI-формы в форму HTTP-ответа клиенту. По сути позволяет использовать консоль ввода и вывода для взаимодействия с клиентом.


Если нужно скрыть код, то нужно пользоваться CGI. Играться буду на Embarcadero Dev-C++. Короче проект должен быть под DOS, и на Си++. Вот простой пример:

1. Создадим проект DOS на C++, назовём проект CGIDemo2025.

2. Напишим следующий код main.cpp:

#include <iostream>

using namespace std;
int main(int argc, char** argv) {
  cout << "Content-Type:text/html\n\r" << endl;
  cout << "<!DOCTYPE HTML><html><head>" << 
  "<title>CGIDemo 2025</title>" <<
  "</head><body><h1 style=\"color:red;\">" << 
  "Hello World!</h1>" <<
  "</body></html>\n";
  return 0;
}


3. Откопилируем проект, созадстся новый файл CGIDemo2025.exe.

4. Скопируем файл CGIDemo2025.exe в папку XAMPP C:\xampp\cgi-bin.

5. Запустим Apache.

6. Запустим браузер и укажем адрес, вуаля! а вот и результат:


Если я кому-то отвечаю, это не значит что я ему симпатизирую, каждый остаётся при своём мнение
#1 
uscheswoi_82 патриот2 дня назад, 08:26
NEW 2 дня назад, 08:26 
в ответ uscheswoi_82 5 дней назад, 16:10

Продолжим вспоминать.

Вообще нужно было так:

cout << "<!DOCTYPE HTML><html><head>" << 
    "<title>CGIDemo 2025</title>" <<
    "</head><body><h1 style=\"color:red;\">" << 
    "Hello World!</h1>" <<
    "</body></html>\n" << endl;

Всегда в конце cout, нужно не забывать << endl;

Если я кому-то отвечаю, это не значит что я ему симпатизирую, каждый остаётся при своём мнение
#2 
uscheswoi_82 патриот2 дня назад, 08:35
NEW 2 дня назад, 08:35 
в ответ uscheswoi_82 2 дня назад, 08:26

Я сегодня написал простенький CGI фреймворк на Си++. Вот код

Request.hpp:

#ifndef _REQUEST
#define _REQUEST
#include <iostream>
#include <string>
using namespace std;
class Request {
private:
  string strContentType;

public:
  ~Request();
  void setContentType(string strContentType);
  string get_method();
  string get_query();
  string get_uri();
  string get_cookies();
};
#endif


Request.cpp:

#include "request.hpp"

void Request::setContentType(string strContentType) {
  this->strContentType = strContentType;
  cout << "Content-Type:" << strContentType << "\n\r" << endl;
}

string Request::get_method() {
  return getenv("REQUEST_METHOD");
}

string Request::get_query() {
  return getenv("QUERY_STRING");
}

string Request::get_uri() {
  return getenv("REQUEST_URI");
}

string Request::get_cookies() {
  return getenv("HTTP_COOKIE");
}


Response.hpp:

#ifndef _RESPONSE
#define _RESPONSE
#include <iostream>
#include <string>

using namespace std;
class Response {
public:
  Response();
  void render(string strData);
};
#endif


Response.cpp:

#include "response.hpp"
Response::Response() {}

void Response::render(string strData) {
  cout << strData << endl;
}


Main.cpp:

#include <iostream>
#include "request.hpp"
#include "response.hpp"


int main(int argc, char** argv) {
  Request *req = new Request();
  Response *resp = new Response();
  req->setContentType("text/html");
  resp->render("<!DOCTYPE HTML><html><head>
               <title>CGIDemo 2025</title> 
               </head><body><h1 style=\"
               color:red;\">Hello World!</h1>
               </body></html>\n");
  return 0;
}



Вуаля а вот и результат!



Если я кому-то отвечаю, это не значит что я ему симпатизирую, каждый остаётся при своём мнение
#3 
uscheswoi_82 патриот2 дня назад, 09:07
NEW 2 дня назад, 09:07 
в ответ uscheswoi_82 2 дня назад, 08:35

Аааа! Ошибка! Так ~Request(); низя, вроде надо так Request();

~ - означает деструктор!!! А нам нужен конструктор т.е. просто Request(); без ~!!!

Request.hpp:

#ifndef _REQUEST
#define _REQUEST
#include <iostream>
#include <string>
using namespace std;
class Request {
private:
  string strContentType;

public:
  Request();
  void setContentType(string strContentType);
  string get_method();
  string get_query();
  string get_uri();
  string get_cookies();
}; 
#endif
Если я кому-то отвечаю, это не значит что я ему симпатизирую, каждый остаётся при своём мнение
#4 
uscheswoi_82 патриот2 дня назад, 09:46
NEW 2 дня назад, 09:46 
в ответ uscheswoi_82 2 дня назад, 09:07

Подправлю. Вместо void Request::setContentType(string strContentType) надо писать void Request::setContentType(string strContentType). Это только в C# и VB NET принято писать так void Request::setContentType(string strContentType). А в Си++, PHP, и Java пишут так set_...() или get_...() и всё маленькими буквами!

Request.hpp:

#ifndef _REQUEST
#define _REQUEST
#include <iostream>
#include <string>
using namespace std;
class Request {
private:
  string strContentType;

public:
  Request();
  void set_content_type(string strContentType);
  string get_method();
  string get_query();
  string get_uri();
  string get_cookies();
};  
#endif


Request.cpp:

#include "request.hpp"

void Request::set_content_type(string strContentType) {
  this->strContentType = strContentType;
  cout << "Content-Type:" << strContentType << "\n\r" << endl;
}

string Request::get_method() {
  return getenv("REQUEST_METHOD");
}

string Request::get_query() {
  return getenv("QUERY_STRING");
}

string Request::get_uri() {
  return getenv("REQUEST_URI");
}

string Request::get_cookies() {
  return getenv("HTTP_COOKIE");
}
Если я кому-то отвечаю, это не значит что я ему симпатизирую, каждый остаётся при своём мнение
#5