start method

Future<void> start(
  1. ServerConfig config
)

Starts the server with the given config.

Binds an HTTP server (or HTTPS if TLS is configured) and begins accepting connections.

Implementation

Future<void> start(ServerConfig config) async {
  if (_status == ServerStatus.running) return;
  _status = ServerStatus.starting;
  _config = config;

  try {
    if (config.tlsCert != null && config.tlsKey != null) {
      final context = SecurityContext()
        ..useCertificateChain(config.tlsCert!)
        ..usePrivateKey(config.tlsKey!);
      _httpServer = await HttpServer.bindSecure(
        config.host,
        config.port,
        context,
      );
    } else {
      _httpServer = await HttpServer.bind(config.host, config.port);
    }

    _httpServer!.idleTimeout = config.idleTimeout;
    _status = ServerStatus.running;

    _httpServer!.listen(
      _handleRequest,
      onError: (Object error) {
        _status = ServerStatus.error;
      },
    );
  } catch (_) {
    _status = ServerStatus.error;
    rethrow;
  }
}