mirror of
https://github.com/ultimatepp/ultimatepp.git
synced 2026-05-15 14:16:07 -06:00
Tutorial, Doc: Added second chapter for network tutorial. It is about building RESTful server.
This commit is contained in:
parent
ec34605fee
commit
9b877c653d
3 changed files with 227 additions and 8 deletions
57
tutorial/Network02/Network02.cpp
Normal file
57
tutorial/Network02/Network02.cpp
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
#include <Core/Core.h>
|
||||
|
||||
using namespace Upp;
|
||||
|
||||
constexpr int port = 4000;
|
||||
|
||||
void ProcessHttpRequest(TcpSocket& client)
|
||||
{
|
||||
HttpHeader header;
|
||||
if(!header.Read(client)) {
|
||||
Cerr() << "Failed to read HttpHeader.\n";
|
||||
HttpResponse(client, false, 400, "Invalid request");
|
||||
return;
|
||||
}
|
||||
|
||||
auto path = header.GetURI();
|
||||
if(header.GetMethod() == "GET") {
|
||||
if(path == "/countries") {
|
||||
JsonArray ja;
|
||||
ja << "Czech Republic"
|
||||
<< "Indonesia"
|
||||
<< "Brazil"
|
||||
<< "France";
|
||||
|
||||
HttpResponse(client, false, 200, "OK", "application/json", ja.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
HttpResponse(client, false, 404, "Not found");
|
||||
}
|
||||
|
||||
void RunServerLoop(TcpSocket& server)
|
||||
{
|
||||
for(;;) {
|
||||
TcpSocket client;
|
||||
|
||||
Cout() << "Waiting for incoming connection from the client...\n";
|
||||
if(!client.Accept(server)) {
|
||||
Cerr() << "Connection from the client not accepted.\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
ProcessHttpRequest(client);
|
||||
}
|
||||
}
|
||||
|
||||
CONSOLE_APP_MAIN
|
||||
{
|
||||
TcpSocket server;
|
||||
if(!server.Listen(port)) {
|
||||
Cerr() << "Cannot open server port for listening with error \"" << server.GetErrorDesc()
|
||||
<< "\".\n";
|
||||
return;
|
||||
}
|
||||
|
||||
RunServerLoop(server);
|
||||
}
|
||||
11
tutorial/Network02/Network02.upp
Normal file
11
tutorial/Network02/Network02.upp
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
description "Creating simple REST service\377";
|
||||
|
||||
uses
|
||||
Core;
|
||||
|
||||
file
|
||||
Network02.cpp;
|
||||
|
||||
mainconfig
|
||||
"" = "";
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue