start method
Starts the server.
If port
is not provided, it will use 8080.
If port
is 0
, it will use a random port chosen by the OS.
If address
is not provided, it will use localhost
, 127.0.0.1
, 0.0.0.0
or ::1
If the server fails to start, it will print an error message and exit with code 1.
If the server starts successfully, it will print a success message, and the server will listen for incoming requests.
If the server is interrupted with Ctrl+C, it will shutdown the server, delete the rate limit file if it exists, and exit with code 0.
Implementation
Future<void> start({String address = '0.0.0.0', int port = 8080}) async {
try {
if (!useHttps) {
print("️🖥️ \x1B[94m️Running in HTTP mode...\x1B[0m");
_server = await HttpServer.bind(address, port);
} else {
SecurityContext securityContext = SecurityContext();
print("️🖥️ \x1B[94mRunning in HTTPS mode...\x1B[0m");
securityContext = SecurityContext(withTrustedRoots: true)
..setTrustedCertificates(sslOptions.certificate);
securityContext.usePrivateKey(sslOptions.keyFile);
securityContext.setAlpnProtocols(['h2', 'http/1.1'], true);
_server = await HttpServer.bindSecure(address, port, securityContext);
}
} on SocketException catch (e) {
if (e.osError!.errorCode == 10048) {
print(
' ❌ \x1B[91mPort is already in use, try to use to a different port.\x1B[0m');
exit(1);
} else {
print(
' ❌ \x1B[91mFailed to start server: OS ERROR ${e.osError!.errorCode}, ${e.osError!.message}\x1B[0m');
exit(1);
}
} catch (e) {
print(' ❌ \x1B[91mFailed to start server:\x1B[0m');
print(e);
exit(1);
}
print(
' 🚀 \x1B[92mServer running on ${_server!.address.address}:${_server!.port}\x1B[0m\n 🛑 Press \x1B[91mCtrl+C\x1B[0m to shutdown the Server.');
emit('serverStarted', {'address': address, 'port': port});
ProcessSignal.sigint.watch().listen((_) async {
final file = File(_rateLimiter!.storagePath);
if (await file.exists()) {
await file.delete();
}
await shutdown();
exit(0);
});
int columns = 48;
String border = '─' * (columns ~/ 2);
const String inverse = '\x1B[7m';
const String reset = '\x1B[0m';
stdout.writeln('$border$inverse LOGS $reset$border\n');
await for (HttpRequest request in _server!) {
await _handleRequest(request, Response(request: request));
}
}