48 lines
2.1 KiB
Markdown
48 lines
2.1 KiB
Markdown
- Все запросы могут обрабатываться одним процессом CGI-программы
|
||
- Веб-сервер взаимодействует с процессом через UNIX Domain Sockets или TCP/IP (а не через stdin и stdout)
|
||
- Для общения используется бинарный протокол, обеспечивающий передачу любых текстовых данных
|
||
## FastCGI на Java
|
||
Пример
|
||
```Java
|
||
public static void main(String[] args) {
|
||
FCGIInterface fcgiInterface = new FCGiInterface();
|
||
while (fcgiInterface.FCGIAccept() >= 0) {
|
||
String content = """
|
||
<html>...</html>
|
||
""";
|
||
String response = """
|
||
HTTP /1.1 200 OK
|
||
Content-Type: text/html
|
||
Content-Length: %d
|
||
|
||
|
||
%s
|
||
""".formatted(content.getBytes(StandardCharsets.UTF_8).length, content);
|
||
}
|
||
}
|
||
```
|
||
- `FCGIInterface` - реализует магию по перенаправлению `System.in`, `System.out` и `System.err` в потоки TCP сокета. Поля для запросов и сокета - статические
|
||
- `FCGIInterface.request.params` - объект `Properties`, через который можно узнать список параметров, переданных веб-сервером
|
||
- Наиболее значимые параметры:
|
||
- `REQUEST_METHOD` - Get, Post и тд
|
||
- `QUERY_STRING` - параметры запроса после `?`
|
||
- `CONTENT_TYPE` - значение заголовка запроса
|
||
- `CONTENT_LENGTH` - значение заголовка запроса
|
||
Еще пример
|
||
```Java
|
||
private static String readRequestBody() throws IOException {
|
||
FCGIInterface.request.inStream.fill();
|
||
|
||
var contentLength = FCGIInterface.request.inStream.available();
|
||
var buffer = ByteBuffer.allocate(contentLength);
|
||
var readBytes = FCGIInterface.request.inStream.read(buffer.array(), 0, contentLength);
|
||
|
||
var requestBodyRaw = new byte[readBytes];
|
||
buffer.get(requestBodyRaw);
|
||
buffer.clear();
|
||
|
||
return new String(requestBodyRaw, StandardCharsets.UTF_8);
|
||
}
|
||
```
|
||
|