CppRoute - Docs

Introduction

Welcome to the documentation for CppRoute lightweight C++ web server framework designed for backend development. cppRoute offers robust POST request handling, flexible routing, and a built-in, text-based database. It processes content types of `application/x-www-form-urlencoded` and is designed to be low-level, allowing users to easily add custom functionality and modify the framework as needed.

This documentation covers all the essential details, including classes, functions, and examples, to help you get started with cppRoute.


Documentation is up-to-date as of September 17th, 2024, but please be aware that changes may have occurred since then.

Classes

Server

Description: The `Server` class is responsible for handling the core operations of your web server, including routing, handling POST requests, managing session variables, and rendering views. It also interacts with a built-in text-based database.

Constructor

explicit Server(int P_PORT)

Parameters:

  • P_PORT: The port number on which the server will listen for incoming connections.

Public Methods

void run_server()

Description: Starts the server and begins listening for incoming connections on the specified port.

void set_assets_routes(const std::string& P_assets_dir)

Description: Sets the directory path for serving static assets like CSS, JavaScript, and images.

Parameters:

  • P_assets_dir: The directory containing the static assets.
void set_views_dir(const std::string& P_views_dir)

Description: Sets the directory path where the server will look for view templates to render.

Parameters:

  • P_views_dir: The directory containing the view templates.
void set_pages_dir(const std::string& P_pages_dir)

Description: Sets the directory path where the server will look for static HTML pages.

Parameters:

  • P_pages_dir: The directory containing the static HTML pages.
void set_databases_dir(const std::string& P_databases_dir)

Description: Sets the directory path where the server will store its text-based databases.

Parameters:

  • P_databases_dir: The directory where database files will be stored.
static std::map[std::string, std::string] parseUrlencodedRequestBody(const std::string& req_body)

Description: Parses a URL-encoded request body into a key-value map.

Parameters:

  • req_body: The URL-encoded request body as a string.

Returns: A map of key-value pairs extracted from the request body.

void route(std::string P_route, std::string P_file_path)

Description: Defines a route for the server and associates it with a file path.

Parameters:

  • P_route: The URL route to handle.
  • P_file_path: The file path to serve when the route is accessed.
void post(std::string P_post_route, std::function[std::string(const std::string& req_body)] func)

Description: Defines a POST route for the server and associates it with a function to handle the POST request.

Parameters:

  • P_post_route: The URL route to handle POST requests.
  • func: A function that takes the request body as input and returns a response.
void add_session_variable(std::string P_name, std::string P_data_type, std::string P_value)

Description: Adds a session variable to the server, storing it with a specific name, data type, and value.

Parameters:

  • P_name: The name of the session variable.
  • P_data_type: The data type of the session variable.
  • P_value: The initial value of the session variable.
void render(std::string file_name)

Description: Renders a specified view or page by its file name.

Parameters:

  • file_name: The name of the file to render.

Private Methods

static bool ends_with(const std::string& str, const std::string& suffix)

Description: Checks if a string ends with a given suffix.

Parameters:

  • str: The string to check.
  • suffix: The suffix to look for.

Returns: true if the string ends with the suffix, false otherwise.

static std::string getSubstringAfterLastChar(const std::string& input, char specialChar)

Description: Extracts the substring that occurs after the last occurrence of a specific character.

Parameters:

  • input: The input string.
  • specialChar: The character after which the substring is extracted.

Returns: The substring after the last occurrence of the specified character.

static std::string get_content_type(const std::string& path)

Description: Determines the content type (MIME type) based on the file extension of the provided path.

Parameters:

  • path: The file path for which to determine the content type.

Returns: The content type corresponding to the file extension.

static void initialize_winsock()

Description: Initializes the Winsock library, required for network operations on Windows.

SOCKET create_server_socket() const

Description: Creates a server socket for accepting client connections.

Returns: A SOCKET object representing the server socket.

static SOCKET accept_client(SOCKET server_socket)

Description: Accepts an incoming client connection on the server socket.

Parameters:

  • server_socket: The server socket that is listening for connections.

Returns: A SOCKET object representing the accepted client connection.

static std::string parse_http_request(const std::string& request)

Description: Parses an incoming HTTP request string to extract the relevant information.

Parameters:

  • request: The raw HTTP request as a string.

Returns: A string containing the parsed request data.

static std::string serve_file(const std::string& path)

Description: Serves the contents of a file located at the given path.

Parameters:

  • path: The path to the file that will be served.

Returns: The contents of the file as a string.

static std::string handle_post_request(const std::string& request, const std::function[std::string(const std::string req_body)]& func)

Description: Handles an incoming POST request, passing the request body to a provided handler function and returning the response.

Parameters:

  • request: The raw HTTP POST request as a string.
  • func: A function that takes the request body as input and returns a response string.

Returns: The response generated by the handler function.

RoutingVector

Description: The `RoutingVector` class is used to define a route in the web server, mapping a specific URL path to a corresponding file path that will be served.

Constructor

RoutingVector(std::string P_route, std::string P_file_path)

Description: Constructs a new `RoutingVector` with the specified route and file path.

Parameters:

  • P_route: The URL route that this `RoutingVector` will handle.
  • P_file_path: The file path that corresponds to the route, which will be served when the route is accessed.

Public Attributes

std::string route

Description: The URL route that this `RoutingVector` is responsible for handling.

std::string file_path

Description: The file path that will be served when the corresponding route is accessed.

PostVector

Description: The `PostVector` class represents a mapping for handling POST requests. It associates a specific POST route with a handler function that processes the request body and generates a response.

Constructor

PostVector(std::string P_post_route, std::function[std::string(std::string req_body)] func)

Description: Constructs a new `PostVector` with the specified POST route and handler function.

Parameters:

  • P_post_route: The POST route that this `PostVector` will handle.
  • func: A function that takes the request body as a string and returns a response string.

Public Attributes

std::string post_route

Description: The POST route that this `PostVector` is responsible for handling.

std::function[std::string(std::string req_body)] handler_function

Description: The function used to handle POST requests. It processes the request body and returns the appropriate response as a string.

SessionVariable

Description: The `SessionVariable` class represents a variable stored in the server's session, including its name, data type, and value.

Constructor

SessionVariable(std::string P_name, std::string P_data_type, std::string P_value)

Description: Constructs a new `SessionVariable` with the specified name, data type, and value.

Parameters:

  • P_name: The name of the session variable.
  • P_data_type: The data type of the session variable (e.g., string, integer).
  • P_value: The value assigned to the session variable.

Public Attributes

std::string name

Description: The name of the session variable, used as its identifier within the session.

std::string data_type

Description: The data type of the session variable, defining the type of data it holds.

std::string value

Description: The value of the session variable, representing the data stored in the session.

Database

Description: The `Database` class provides functionality for managing tables and performing database operations such as creating tables, inserting data, querying, and saving/loading data from files. It operates in conjunction with the `Server` class.

Constructor

Database(Server& server)

Description: Constructs a new `Database` object and associates it with the given `Server` instance.

Parameters:

  • server: A reference to the `Server` instance that this `Database` will interact with.

Public Methods

void createTable(const std::string& name, const std::vector[std::string]& columns)

Description: Creates a new table with the specified name and columns.

Parameters:

  • name: The name of the table to be created.
  • columns: A vector of column names for the new table.
void insert(const std::string& tableName, const std::vector[std::string]& values)

Description: Inserts a new row with the specified values into the specified table.

Parameters:

  • tableName: The name of the table where the data will be inserted.
  • values: A vector of values to be inserted into the table.
Table* getTable(const std::string& tableName)

Description: Retrieves a pointer to the table with the specified name.

Parameters:

  • tableName: The name of the table to retrieve.

Returns: A pointer to the `Table` object if found, otherwise nullptr.

std::vector[Row] query(const std::string& tableName, std::function[bool(const Row&)] condition)

Description: Queries the specified table with the given condition function and returns the rows that satisfy the condition.

Parameters:

  • tableName: The name of the table to query.
  • condition: A function that takes a row and returns true if the row meets the condition, otherwise false.

Returns: A vector of `Row` objects that match the query condition.

void printTable(const std::string& tableName) const

Description: Prints the contents of the specified table to the console.

Parameters:

  • tableName: The name of the table to print.
void saveToFile(const std::string& filename)

Description: Saves the database contents to a file.

Parameters:

  • filename: The name of the file to save the database to.
void loadFromFile(const std::string& filename)

Description: Loads the database contents from a file.

Parameters:

  • filename: The name of the file to load the database from.

Row

Description: The `Row` class represents a single row of data within a `Table`. It consists of a vector of values and provides methods to serialize and deserialize the row data.

Constructor

Row(const std::vector[std::string]& values)

Description: Constructs a new `Row` object with the specified vector of values.

Parameters:

  • values: A vector of strings representing the values for each column in the row.

Public Methods

std::string serialize() const

Description: Serializes the `Row` object into a string format suitable for storage or transmission.

Returns: A string representation of the `Row` object.

static Row deserialize(const std::string& str)

Description: Deserializes a string into a `Row` object.

Parameters:

  • str: A string representing a serialized `Row` object.

Returns: A `Row` object constructed from the serialized string.

Table

Description: The `Table` class represents a collection of rows and provides methods to manipulate and access the data within the table. It includes operations for inserting rows, selecting data, and serializing/deserializing the table.

Constructor

Table(const std::string name, const std::vector[std::string]& columns)

Description: Constructs a new `Table` object with the specified name and column names.

Parameters:

  • name: The name of the table.
  • columns: A vector of strings representing the column names for the table.

Public Methods

void insertRow(const std::vector[std::string]& values)

Description: Inserts a new row into the table with the specified values. The number of values should match the number of columns in the table.

Parameters:

  • values: A vector of strings representing the values to be inserted into the row.
std::vector[Row] select(std::function[bool(const Row&)] condition) const

Description: Selects and returns rows that satisfy the given condition function.

Parameters:

  • condition: A function that takes a `Row` and returns true if the row meets the condition, otherwise false.

Returns: A vector of `Row` objects that meet the condition.

void printTable() const

Description: Prints the table's contents to the console.

std::string serialize() const

Description: Serializes the `Table` object into a string format suitable for storage or transmission.

Returns: A string representation of the `Table` object.

static Table deserialize(const std::string& name, const std::string& str)

Description: Deserializes a string into a `Table` object.

Parameters:

  • name: The name of the table.
  • str: A string representing a serialized `Table` object.

Returns: A `Table` object constructed from the serialized string.

Examples

How to create a simple website with a POST request:

main.cpp


                            #include "Server/Server.h"
                            #include "functions.h"
                            /* functions.h ->
                            
                                #ifndef FUNCTIONS_H
                                #define FUNCTIONS_H
                            
                                // Initialize your functions here.
                            
                                std::string multiplyThree(const std::string& req_body);
                            
                                #endif //FUNCTIONS_H
                            
                            */
                            
                            int main() {
                            
                                Server server{3000};
                            
                                server.set_pages_dir("./www");
                            
                                // Serve math.html
                                server.route("/math", "/www/math.html");
                                server.route("/math.js", "/www/math.js");
                                server.post("/multiplyThree", multiplyThree);
                            
                                server.run_server();
                                return 0;
                            }
                            
                            
                            std::string multiplyThree(const std::string& req_body) {
                                std::map[std::string, std::string] params = Server::parseUrlencodedRequestBody(req_body);
                            
                                const int num1 = std::stoi(params["num1"]);
                                const int num2 = std::stoi(params["num2"]);
                                const int num3 = std::stoi(params["num3"]);
                            
                                const int result = num1 * num2 * num3;
                            
                                std::ostringstream response_stream;
                                response_stream << "HTTP/1.1 200 OK\r\n";
                                response_stream << "Content-Length: " << std::to_string(result).length() << "\r\n";
                                response_stream << "Content-Type: text/plain\r\n\r\n";
                                response_stream << result;
                            
                                return response_stream.str();
                            }
                            

www/math.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple Web Server Test</title> </head> <body> <h1>Simple Web Server Test</h1> <h2>Multiply a number by another number by another number</h2> <p>Enter a number to multiply:</p> <input type="number" id="inputNumberOne" placeholder="Enter a number"> <input type="number" id="inputNumberTwo" placeholder="Enter a number"> <input type="number" id="inputNumberThree" placeholder="Enter a number"> <button onclick="sendPostRequest()">Submit</button> <h2>Result:</h2> <p id="result"></p> <script src="math.js"> </script> </body> </html>

www/math.js

async function sendPostRequest() { // Parameters to send const params = new URLSearchParams(); params.append('num1', document.getElementById("inputNumberOne").value); params.append('num2', document.getElementById("inputNumberTwo").value); params.append('num3', document.getElementById("inputNumberThree").value); try { const response = await fetch('/multiplyThree', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: params.toString(), }); // Check if the response is okay if (!response.ok) { throw new Error('Network response was not ok'); } // Parse the response const result = await response.text(); document.getElementById("result").innerText = result; } catch (error) { console.error('Fetch error:', error); } }