ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
ascii_query::HttpServer Class Reference

Simple single-threaded HTTP server. More...

#include <src/tooling/query/http_server.h>

Public Member Functions

 HttpServer ()
 ~HttpServer ()
 HttpServer (const HttpServer &)=delete
HttpServer & operator= (const HttpServer &)=delete
void addRoute (const std::string &method, const std::string &path, RouteHandler handler)
 Add a route handler.
void setDefaultHandler (RouteHandler handler)
 Set a default handler for unmatched routes.
bool start (uint16_t port)
 Start the server.
void stop ()
 Stop the server.
bool isRunning () const
 Check if server is running.
uint16_t port () const
 Get the port the server is listening on.
const std::string & lastError () const
 Get the last error message.
bool processOneRequest ()
 Process one request (blocking).

Detailed Description

Simple single-threaded HTTP server.

Definition at line 162 of file http_server.h.

Constructor & Destructor Documentation

◆ HttpServer() [1/2]

ascii_query::HttpServer::HttpServer ( )

Definition at line 111 of file http_server.cpp.

111 {
112#if defined(_WIN32)
113 // Initialize Winsock
114 WSADATA wsa_data;
115 WSAStartup(MAKEWORD(2, 2), &wsa_data);
116#endif
117
118 // Default 404 handler
119 default_handler_ = [](const HttpRequest &) { return HttpResponse::notFound(); };
120}
static HttpResponse notFound(const std::string &message="Not Found")

References ascii_query::HttpResponse::notFound().

Referenced by HttpServer(), and operator=().

◆ ~HttpServer()

ascii_query::HttpServer::~HttpServer ( )

Definition at line 122 of file http_server.cpp.

122 {
123 stop();
124
125#if defined(_WIN32)
126 WSACleanup();
127#endif
128}
void stop()
Stop the server.

References stop().

◆ HttpServer() [2/2]

ascii_query::HttpServer::HttpServer ( const HttpServer & )
delete

References HttpServer().

Member Function Documentation

◆ addRoute()

void ascii_query::HttpServer::addRoute ( const std::string & method,
const std::string & path,
RouteHandler handler )

Add a route handler.

Parameters
methodHTTP method (GET, POST, etc.)
pathURL path (exact match)
handlerHandler function

Definition at line 130 of file http_server.cpp.

130 {
131 routes_.push_back({method, path, std::move(handler)});
132}

◆ isRunning()

bool ascii_query::HttpServer::isRunning ( ) const
inlinenodiscard

Check if server is running.

Definition at line 200 of file http_server.h.

200 {
201 return running_;
202 }

◆ lastError()

const std::string & ascii_query::HttpServer::lastError ( ) const
inlinenodiscard

Get the last error message.

Definition at line 214 of file http_server.h.

214 {
215 return last_error_;
216 }

Referenced by main().

◆ operator=()

HttpServer & ascii_query::HttpServer::operator= ( const HttpServer & )
delete

References HttpServer(), and port().

◆ port()

uint16_t ascii_query::HttpServer::port ( ) const
inlinenodiscard

Get the port the server is listening on.

Definition at line 207 of file http_server.h.

207 {
208 return port_;
209 }

Referenced by operator=(), and start().

◆ processOneRequest()

bool ascii_query::HttpServer::processOneRequest ( )

Process one request (blocking).

Used for testing or manual control. Normally you'd call start() instead.

Returns
true if a request was processed, false on error

Definition at line 232 of file http_server.cpp.

232 {
233 if (server_socket_ < 0) {
234 return false;
235 }
236
237 struct sockaddr_in client_addr{};
238 socklen_t client_len = sizeof(client_addr);
239
240 socket_t client_socket = accept(server_socket_, reinterpret_cast<struct sockaddr *>(&client_addr), &client_len);
241
242 if (client_socket == INVALID_SOCKET_VAL) {
243 return false;
244 }
245
246 handleClient(static_cast<int>(client_socket));
247 return true;
248}
#define INVALID_SOCKET_VAL
int socket_t

References INVALID_SOCKET_VAL.

◆ setDefaultHandler()

void ascii_query::HttpServer::setDefaultHandler ( RouteHandler handler)

Set a default handler for unmatched routes.

Parameters
handlerHandler function

Definition at line 134 of file http_server.cpp.

134 {
135 default_handler_ = std::move(handler);
136}

◆ start()

bool ascii_query::HttpServer::start ( uint16_t port)

Start the server.

Parameters
portPort to listen on
Returns
true if server started successfully

Definition at line 138 of file http_server.cpp.

138 {
139 if (running_) {
140 last_error_ = "Server already running";
141 return false;
142 }
143
144 // Create socket
145 server_socket_ = static_cast<int>(socket(AF_INET, SOCK_STREAM, 0));
146 if (server_socket_ == INVALID_SOCKET_VAL) {
147 last_error_ = "Failed to create socket";
148 return false;
149 }
150
151 // Set SO_REUSEADDR
152 int opt = 1;
153#if defined(_WIN32)
154 setsockopt(server_socket_, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char *>(&opt), sizeof(opt));
155#else
156 setsockopt(server_socket_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
157#endif
158
159 // Bind
160 struct sockaddr_in addr{};
161 addr.sin_family = AF_INET;
162 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // localhost only for security
163 addr.sin_port = htons(port);
164
165 if (bind(server_socket_, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)) < 0) {
166 last_error_ = "Failed to bind to port " + std::to_string(port);
167 close_socket(server_socket_);
168 server_socket_ = -1;
169 return false;
170 }
171
172 // Listen
173 if (listen(server_socket_, 10) < 0) {
174 last_error_ = "Failed to listen on socket";
175 close_socket(server_socket_);
176 server_socket_ = -1;
177 return false;
178 }
179
180 port_ = port;
181 running_ = true;
182
183 // Start server thread
184 server_thread_ = std::thread(&HttpServer::serverLoop, this);
185
186 return true;
187}
uint16_t port() const
Get the port the server is listening on.
#define close_socket

References close_socket, INVALID_SOCKET_VAL, and port().

Referenced by main().

◆ stop()

void ascii_query::HttpServer::stop ( )

Stop the server.

Definition at line 189 of file http_server.cpp.

189 {
190 if (!running_) {
191 return;
192 }
193
194 running_ = false;
195
196 // Close server socket to unblock accept()
197 if (server_socket_ >= 0) {
198#if defined(_WIN32)
199 shutdown(server_socket_, SD_BOTH);
200#else
201 shutdown(server_socket_, SHUT_RDWR);
202#endif
203 close_socket(server_socket_);
204 server_socket_ = -1;
205 }
206
207 // Wait for server thread
208 if (server_thread_.joinable()) {
209 server_thread_.join();
210 }
211}

References close_socket.

Referenced by main(), and ~HttpServer().


The documentation for this class was generated from the following files: