├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── analysis_options.yaml ├── example ├── README.md ├── commands.dart ├── pubspec.yaml └── simple.dart ├── lib ├── isohttpd.dart └── src │ ├── logger.dart │ ├── models │ ├── request_log.dart │ ├── router.dart │ └── state.dart │ ├── request_logger.dart │ ├── runner.dart │ ├── server.dart │ ├── types.dart │ └── utils.dart └── pubspec.yaml /.gitignore: -------------------------------------------------------------------------------- 1 | Miscellaneous 2 | *.class 3 | *.lock 4 | *.log 5 | *.pyc 6 | *.swp 7 | .DS_Store 8 | .atom/ 9 | .buildlog/ 10 | .history 11 | .svn/ 12 | 13 | # IntelliJ related 14 | *.iml 15 | *.ipr 16 | *.iws 17 | .idea/ 18 | 19 | # Visual Studio Code related 20 | .vscode/ 21 | 22 | # Sphinx documentation 23 | docs/_build/ 24 | 25 | # Flutter/Dart/Pub related 26 | **/doc/api/ 27 | .dart_tool/ 28 | .flutter-plugins 29 | .packages 30 | .pub-cache/ 31 | .pub/ 32 | build/ 33 | 34 | # Android related 35 | **/android/**/gradle-wrapper.jar 36 | **/android/.gradle 37 | **/android/captures/ 38 | **/android/gradlew 39 | **/android/gradlew.bat 40 | **/android/local.properties 41 | **/android/**/GeneratedPluginRegistrant.java 42 | 43 | # iOS/XCode related 44 | **/ios/**/*.mode1v3 45 | **/ios/**/*.mode2v3 46 | **/ios/**/*.moved-aside 47 | **/ios/**/*.pbxuser 48 | **/ios/**/*.perspectivev3 49 | **/ios/**/*sync/ 50 | **/ios/**/.sconsign.dblite 51 | **/ios/**/.tags* 52 | **/ios/**/.vagrant/ 53 | **/ios/**/DerivedData/ 54 | **/ios/**/Icon? 55 | **/ios/**/Pods/ 56 | **/ios/**/.symlinks/ 57 | **/ios/**/profile 58 | **/ios/**/xcuserdata 59 | **/ios/.generated/ 60 | **/ios/Flutter/App.framework 61 | **/ios/Flutter/Flutter.framework 62 | **/ios/Flutter/Generated.xcconfig 63 | **/ios/Flutter/app.flx 64 | **/ios/Flutter/app.zip 65 | **/ios/Flutter/flutter_assets/ 66 | **/ios/ServiceDefinitions.json 67 | **/ios/Runner/GeneratedPluginRegistrant.* 68 | 69 | # Exceptions to above rules. 70 | !**/ios/**/default.mode1v3 71 | !**/ios/**/default.mode2v3 72 | !**/ios/**/default.pbxuser 73 | !**/ios/**/default.perspectivev3 74 | !/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages 75 | 76 | # Coverage report 77 | coverage/output/ 78 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 0.5.0 4 | 5 | Update dependencies 6 | 7 | ## 0.4.0 8 | 9 | Improve the logging 10 | 11 | ## 0.3.0 12 | 13 | - Fix socket close an dispose 14 | - Use more strict analysis options 15 | - Add docstrings 16 | 17 | ## 0.2.0 18 | 19 | - Use pedantic for analysis options 20 | - Use typed data for logs streams 21 | - Linting 22 | 23 | ## 0.1.0 24 | 25 | Initial 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 synw 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Isohttpd 2 | 3 | [![pub package](https://img.shields.io/pub/v/isohttpd.svg)](https://pub.dartlang.org/packages/isohttpd) 4 | 5 | A lightweight http server that runs in an isolate. Powered by [Iso](https://github.com/synw/iso) 6 | 7 | ## Example 8 | 9 | ```dart 10 | import 'dart:io'; 11 | import 'dart:async'; 12 | import 'package:isohttpd/isohttpd.dart'; 13 | 14 | Future handler(HttpRequest request, IsoLogger log) async { 15 | return jsonResponse(request, {"response": "ok"}); 16 | } 17 | 18 | void main() async { 19 | // set routes 20 | final defaultRoute = IsoRoute(path: "*", handler: handler); 21 | final routes = [defaultRoute]; 22 | final router = IsoRouter(routes); 23 | 24 | // run 25 | final iso = IsoHttpdRunner(host: "localhost", router: router); 26 | await iso.run(verbose: true); 27 | 28 | // listen to logs 29 | iso.logs.listen((String data) => print("$data")); 30 | iso.requestLogs.listen((ServerRequestLog data) => print("=> $data")); 31 | // idle 32 | final waiter = Completer(); 33 | await waiter.future; 34 | } 35 | ``` 36 | 37 | ## Commands 38 | 39 | Start the server: 40 | 41 | ```dart 42 | await iso.run(startServer: false); 43 | iso.start(); 44 | ``` 45 | 46 | Stop the server: 47 | 48 | ```dart 49 | iso.stop(); 50 | ``` 51 | 52 | Server status: 53 | 54 | ```dart 55 | iso.status(); 56 | ``` 57 | 58 | ## Utils 59 | 60 | Send a json response from a handler: 61 | 62 | ```dart 63 | jsonResponse(request, {"response": "ok"}); 64 | ``` 65 | 66 | Decode multipart/form-data: 67 | 68 | ```dart 69 | final body = await decodeMultipartRequest(request); 70 | final dynamic data = body.data; 71 | ``` 72 | 73 | List a directory's content: 74 | 75 | ```dart 76 | final data = await directoryListing(Directory(somePath)); 77 | ``` 78 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:extra_pedantic/analysis_options.yaml 2 | 3 | analyzer: 4 | strong-mode: 5 | implicit-casts: false 6 | implicit-dynamic: false 7 | errors: 8 | missing_return: error 9 | missing_required_param: error 10 | invalid_use_of_protected_member: error 11 | dead_code: info 12 | sdk_version_async_exported_from_core: ignore 13 | linter: 14 | rules: 15 | - unnecessary_statements 16 | - unnecessary_lambdas 17 | - avoid_classes_with_only_static_members 18 | - avoid_renaming_method_parameters 19 | - camel_case_types 20 | - constant_identifier_names 21 | - cascade_invocations 22 | - omit_local_variable_types 23 | - public_member_api_docs 24 | #- avoid_bool_literals_in_conditional_expressions 25 | #- avoid_positional_boolean_parameters -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | 3 | Command line example: 4 | 5 | ```dart 6 | Future handler(HttpRequest request, IsoLogger log) async { 7 | request.response.statusCode = HttpStatus.ok; 8 | return request.response; 9 | } 10 | 11 | Future initHost() async { 12 | final interfaces = await NetworkInterface.list( 13 | includeLoopback: false, type: InternetAddressType.any); 14 | return interfaces.first.addresses.first.address; 15 | } 16 | 17 | void main() async { 18 | // set routes 19 | IsoRoute onGet = IsoRoute(path: "*", handler: handler); 20 | List routes = [onGet]; 21 | final router = IsoRouter(routes); 22 | // set host 23 | String host = await initHost(); 24 | // run 25 | print("Running the server in an isolate"); 26 | IsoHttpdRunner iso = IsoHttpdRunner(host: host, router: router); 27 | await iso.run(verbose: true); 28 | // listen to logs 29 | iso.logs.listen((dynamic data) => print("$data")); 30 | iso.requestLogs.listen((dynamic data) => print("REQUEST $data")); 31 | // idle 32 | while (true) {} 33 | } 34 | ``` 35 | -------------------------------------------------------------------------------- /example/commands.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | import 'dart:io'; 3 | 4 | import 'package:isohttpd/isohttpd.dart'; 5 | 6 | Future handler(HttpRequest request, IsoLogger log) async { 7 | log.push("Hello from request handler"); 8 | return jsonResponse(request, {"response": "ok"}); 9 | } 10 | 11 | Future initHost() async { 12 | final interfaces = await NetworkInterface.list( 13 | includeLoopback: false, type: InternetAddressType.any); 14 | return interfaces.first.addresses.first.address; 15 | } 16 | 17 | Future main() async { 18 | /// set routes 19 | final defaultRoute = IsoRoute(path: "*", handler: handler); 20 | final routes = [defaultRoute]; 21 | final router = IsoRouter(routes); 22 | 23 | /// set host 24 | final host = await initHost(); 25 | 26 | /// init runner 27 | final iso = IsoHttpd(host: host, router: router); 28 | 29 | /// listen to logs 30 | iso.logs.listen((dynamic msg) => print("[server log] $msg")); 31 | iso.requestLogs.listen((ServerRequestLog data) => print("=> $data")); 32 | 33 | /// run 34 | print("Running the server in an isolate"); 35 | await iso.run(startServer: false); 36 | iso 37 | ..status() 38 | ..start(); 39 | await iso.onServerStarted; 40 | iso.status(); 41 | await Future.delayed(const Duration(seconds: 3)); 42 | print("Stopping the server"); 43 | iso 44 | ..stop() 45 | ..status(); 46 | //iso.dispose(); 47 | } 48 | -------------------------------------------------------------------------------- /example/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: isohttpd_example 2 | description: A http server 3 | # version: 1.0.0 4 | # homepage: https://www.example.com 5 | # author: Your Name 6 | 7 | environment: 8 | sdk: '>=2.2.0 <3.0.0' 9 | 10 | #dependencies: 11 | # path: ^1.4.1 12 | 13 | dev_dependencies: 14 | test: ^1.0.0 15 | 16 | dependencies: 17 | isohttpd: 18 | path: ../ 19 | -------------------------------------------------------------------------------- /example/simple.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | import 'dart:io'; 3 | 4 | import 'package:isohttpd/isohttpd.dart'; 5 | 6 | Future handler(HttpRequest request, IsoLogger log) async { 7 | log.push("Hello from request handler"); 8 | return jsonResponse(request, {"response": "ok"}); 9 | } 10 | 11 | Future initHost() async { 12 | final interfaces = await NetworkInterface.list( 13 | includeLoopback: false, type: InternetAddressType.any); 14 | return interfaces.first.addresses.first.address; 15 | } 16 | 17 | Future main() async { 18 | /// set routes 19 | final defaultRoute = IsoRoute(path: "*", handler: handler); 20 | final routes = [defaultRoute]; 21 | final router = IsoRouter(routes); 22 | 23 | /// set host 24 | final host = await initHost(); 25 | 26 | /// init runner 27 | final iso = IsoHttpd(host: host, router: router); 28 | 29 | /// listen to logs 30 | iso.logs.listen((dynamic msg) => print("[server log] $msg")); 31 | iso.requestLogs.listen((ServerRequestLog data) => print("=> $data")); 32 | 33 | /// run 34 | print("Running the server in an isolate"); 35 | await iso.run(); 36 | } 37 | -------------------------------------------------------------------------------- /lib/isohttpd.dart: -------------------------------------------------------------------------------- 1 | /// Isohttpd server 2 | /// 3 | /// An http server 4 | library isohttpd; 5 | 6 | export 'src/logger.dart'; 7 | export 'src/logger.dart'; 8 | export 'src/models/request_log.dart'; 9 | export 'src/models/router.dart'; 10 | export 'src/runner.dart'; 11 | export 'src/types.dart'; 12 | export 'src/utils.dart'; 13 | -------------------------------------------------------------------------------- /lib/src/logger.dart: -------------------------------------------------------------------------------- 1 | import 'dart:isolate'; 2 | 3 | import 'package:meta/meta.dart'; 4 | 5 | /// The logger 6 | class IsoLogger { 7 | /// Default constructor 8 | IsoLogger({@required this.chan}) : assert(chan != null); 9 | 10 | /// The port to use 11 | final SendPort chan; 12 | 13 | /// Push something to the logs 14 | void push(dynamic obj) => chan.send(obj); 15 | } 16 | -------------------------------------------------------------------------------- /lib/src/models/request_log.dart: -------------------------------------------------------------------------------- 1 | import 'package:meta/meta.dart'; 2 | 3 | import '../types.dart'; 4 | 5 | /// A log message for request 6 | class ServerRequestLog { 7 | /// Default constructor 8 | ServerRequestLog( 9 | {@required this.requestUrl, 10 | @required this.message, 11 | @required this.statusCode, 12 | @required this.logClass}) { 13 | time = DateTime.now().toLocal(); 14 | } 15 | 16 | /// The time of the request 17 | DateTime time; 18 | 19 | /// The url 20 | String requestUrl; 21 | 22 | /// The log message 23 | final String message; 24 | 25 | /// The http status code 26 | final int statusCode; 27 | 28 | /// The log level 29 | final LogMessageClass logClass; 30 | 31 | @override 32 | String toString() { 33 | final date = "${time.hour}:${time.minute}:${time.second}"; 34 | String msgClass; 35 | switch (logClass) { 36 | case LogMessageClass.success: 37 | msgClass = "[OK]"; 38 | break; 39 | case LogMessageClass.warning: 40 | msgClass = "[WARNING]"; 41 | break; 42 | case LogMessageClass.error: 43 | msgClass = "[ERROR]"; 44 | break; 45 | default: 46 | } 47 | if (requestUrl == "") requestUrl = "/"; 48 | final msg = "$date $statusCode $msgClass $requestUrl $message"; 49 | return msg; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /lib/src/models/router.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import 'package:meta/meta.dart'; 4 | 5 | import '../logger.dart'; 6 | import '../types.dart'; 7 | 8 | /// The http routed 9 | class IsoRouter { 10 | /// Default constructor 11 | IsoRouter(this.routes); 12 | 13 | /// The available routes 14 | List routes; 15 | } 16 | 17 | /// Http route 18 | class IsoRoute { 19 | /// If not [handler] is provided it will just print the request 20 | IsoRoute({@required this.path, this.handler}) { 21 | handler ??= (HttpRequest request, IsoLogger logSink) async { 22 | print("Request: ${request.uri}"); 23 | return request.response; 24 | }; 25 | } 26 | 27 | /// The url path 28 | final String path; 29 | 30 | /// The requests handler 31 | IsoRequestHandler handler; 32 | } 33 | -------------------------------------------------------------------------------- /lib/src/models/state.dart: -------------------------------------------------------------------------------- 1 | import '../types.dart'; 2 | 3 | /// The server state 4 | class ServerState { 5 | /// Default constructor 6 | const ServerState(this.status); 7 | 8 | /// Status of the server 9 | final ServerStatus status; 10 | } 11 | -------------------------------------------------------------------------------- /lib/src/request_logger.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | import 'dart:io'; 3 | import 'dart:isolate'; 4 | 5 | import 'package:meta/meta.dart'; 6 | 7 | import 'models/request_log.dart'; 8 | import 'types.dart'; 9 | 10 | /// The requests logger 11 | class IsoRequestLogger { 12 | /// Default constructor 13 | IsoRequestLogger( 14 | {@required this.logChannel, this.chan, this.verbose = false}); 15 | 16 | /// The logs stream 17 | final StreamController logChannel; 18 | 19 | /// The port to use 20 | final SendPort chan; 21 | 22 | /// Verbosity 23 | final bool verbose; 24 | 25 | /// Success level 26 | void success(String msg, HttpRequest request) { 27 | final logItem = ServerRequestLog( 28 | logClass: LogMessageClass.success, 29 | statusCode: request.response.statusCode, 30 | requestUrl: request.uri.path, 31 | message: msg); 32 | _processMsg(logItem); 33 | } 34 | 35 | /// Warning level 36 | void warning(String msg, HttpRequest request) { 37 | final logItem = ServerRequestLog( 38 | logClass: LogMessageClass.warning, 39 | statusCode: request.response.statusCode, 40 | requestUrl: request.uri.path, 41 | message: msg); 42 | _processMsg(logItem); 43 | } 44 | 45 | /// Error level 46 | void error(String msg, HttpRequest request) { 47 | final logItem = ServerRequestLog( 48 | logClass: LogMessageClass.error, 49 | statusCode: request.response.statusCode, 50 | requestUrl: request.uri.path, 51 | message: msg); 52 | _processMsg(logItem); 53 | } 54 | 55 | void _processMsg(ServerRequestLog logItem) { 56 | //if (verbose) print(logItem); 57 | logChannel.sink.add(logItem); 58 | //if (chan != null) chan.send(logItem); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /lib/src/runner.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | 3 | import 'package:iso/iso.dart'; 4 | import 'package:meta/meta.dart'; 5 | import 'package:pedantic/pedantic.dart'; 6 | import 'package:emodebug/emodebug.dart'; 7 | 8 | import 'models/request_log.dart'; 9 | import 'models/router.dart'; 10 | import 'models/state.dart'; 11 | import 'server.dart'; 12 | import 'types.dart'; 13 | 14 | /// The server runner class 15 | class IsoHttpd { 16 | /// Default constructor 17 | IsoHttpd( 18 | {@required this.host, 19 | @required this.router, 20 | this.apiKey, 21 | this.port = 8084, 22 | this.textDebug = false}) { 23 | if (!textDebug) { 24 | _ = const EmoDebug(deactivatePrint: true); 25 | } else { 26 | _ = const EmoDebug(deactivatePrint: true, deactivateEmojis: true); 27 | } 28 | } 29 | 30 | /// The host to serve from 31 | final String host; 32 | 33 | /// The port 34 | int port; 35 | 36 | /// The iso router 37 | final IsoRouter router; 38 | 39 | /// an optional api key 40 | final String apiKey; 41 | 42 | /// Disable emojis in debug 43 | final bool textDebug; 44 | 45 | /// The main iso instance 46 | Iso iso; 47 | 48 | final _logsController = StreamController.broadcast(); 49 | final _requestLogsController = StreamController.broadcast(); 50 | StreamSubscription _dataOutSub; 51 | var _serverStartedCompleter = Completer(); 52 | final _ready = Completer(); 53 | bool _isRunning; 54 | EmoDebug _; 55 | 56 | /// Server logs stream 57 | Stream get logs => _logsController.stream; 58 | 59 | /// Request logs stream 60 | Stream get requestLogs => _requestLogsController.stream; 61 | 62 | /// The server has started event 63 | Future get onServerStarted => _serverStartedCompleter.future; 64 | 65 | /// The server is ready to use 66 | Future get onReady => _ready.future; 67 | 68 | /// Is the server running? 69 | bool get isRunning => _isRunning; 70 | 71 | static Future _run(IsoRunner isoRunner) async { 72 | isoRunner.receive(); 73 | // get config from args 74 | IsoHttpdServer server; 75 | String _host; 76 | int _port; 77 | IsoRouter _router; 78 | String _apiKey; 79 | bool _startServer; 80 | final data = isoRunner.args[0] as Map; 81 | _host = data["host"] as String; 82 | _port = data["port"] as int; 83 | _router = data["router"] as IsoRouter; 84 | _startServer = data["start_server"] as bool; 85 | if (data.containsKey("api_key") == true) { 86 | _apiKey = data["api_key"] as String; 87 | } 88 | /*print("ROUTER $_router"); 89 | for (final r in _router.routes) { 90 | print("- Route ${r.path} / ${r.handler}"); 91 | }*/ 92 | // init server instance 93 | server = IsoHttpdServer( 94 | host: _host, 95 | port: _port, 96 | router: _router, 97 | apiKey: _apiKey, 98 | chan: isoRunner.chanOut) 99 | ..init(); 100 | isoRunner.send(ServerStatus.ready); 101 | //print('R > server init completed'); 102 | if (_startServer) { 103 | //print("R > start server"); 104 | await server.onReady; 105 | //chan.send("RCHAN > server ready"); 106 | await server.start(); 107 | isoRunner.send(ServerStatus.started); 108 | //chan.send("RCHAN > server started"); 109 | } 110 | isoRunner.dataIn.listen((dynamic data) async { 111 | //print("R > DATA IN $data"); 112 | final cmd = data as HttpdCommand; 113 | switch (cmd) { 114 | case HttpdCommand.start: 115 | if (server.status == ServerStatus.started) { 116 | isoRunner.send(ServerError.alreadyStarted); 117 | } else { 118 | await server.onReady; 119 | try { 120 | await server.start(); 121 | } catch (_) { 122 | rethrow; 123 | } 124 | unawaited(server.onStarted 125 | .then((_) => isoRunner.send(ServerStatus.started))); 126 | } 127 | break; 128 | case HttpdCommand.stop: 129 | if (server.status == ServerStatus.stopped) { 130 | isoRunner.send(ServerError.notRunning); 131 | } else { 132 | try { 133 | server.stop(); 134 | isoRunner.send(ServerStatus.stopped); 135 | } catch (e) { 136 | rethrow; 137 | } 138 | } 139 | break; 140 | case HttpdCommand.status: 141 | isoRunner.send(ServerState(server.status)); 142 | } 143 | }); 144 | } 145 | 146 | /// Start the server command 147 | void start() => iso.send(HttpdCommand.start); 148 | 149 | /// Stop the server command 150 | void stop() => iso.send(HttpdCommand.stop); 151 | 152 | /// Server status command 153 | void status() => iso.send(HttpdCommand.status); 154 | 155 | /// Run the server in an isolate 156 | Future run({bool startServer = true}) async { 157 | assert(host != null); 158 | assert(router != null); 159 | iso = Iso(_run, onDataOut: (dynamic data) => null); 160 | 161 | // logs relay 162 | _dataOutSub = iso.dataOut.listen((dynamic data) { 163 | //print("DATA OUT $data / ${data.runtimeType}"); 164 | if (data is ServerRequestLog) { 165 | //print("RUN > REQUEST LOG DATA $data"); 166 | _addToRequestLogs(data); 167 | } else if (data is String) { 168 | _addToLogs(data); 169 | } else if (data is ServerStatus) { 170 | switch (data) { 171 | case ServerStatus.started: 172 | if (!_serverStartedCompleter.isCompleted) { 173 | _isRunning = true; 174 | _serverStartedCompleter.complete(); 175 | _addToLogs(_.start("Server started at $host:$port")); 176 | } 177 | break; 178 | case ServerStatus.stopped: 179 | _serverStartedCompleter = Completer(); 180 | _isRunning = false; 181 | _addToLogs(_.stop("Server stopped")); 182 | break; 183 | case ServerStatus.ready: 184 | _ready.complete(); 185 | } 186 | } else if (data is ServerError) { 187 | switch (data) { 188 | case ServerError.alreadyStarted: 189 | _addToLogs(_.warning("The server is already started")); 190 | break; 191 | case ServerError.notRunning: 192 | _addToLogs(_.warning("Error: the server is not running")); 193 | break; 194 | } 195 | } else if (data is ServerState) { 196 | String status; 197 | switch (data.status) { 198 | case ServerStatus.started: 199 | status = "running"; 200 | break; 201 | case ServerStatus.stopped: 202 | status = "not running"; 203 | break; 204 | default: 205 | } 206 | _addToLogs(_.msg("Server status: $status")); 207 | } else { 208 | //print("RUN > LOG DATA $data"); 209 | _addToLogs(data); 210 | } 211 | }); 212 | 213 | // configure the run function parameters 214 | final conf = { 215 | "host": host, 216 | "port": port, 217 | "router": router, 218 | "api_key": apiKey, 219 | "start_server": startServer 220 | }; 221 | // run 222 | await iso.run([conf]); 223 | await iso.onCanReceive; 224 | } 225 | 226 | /// Kill the server 227 | void kill() { 228 | iso.dispose(); 229 | _dispose(); 230 | } 231 | 232 | /// Dispose streams 233 | void _dispose() { 234 | _dataOutSub.cancel(); 235 | _requestLogsController.close(); 236 | _logsController.close(); 237 | } 238 | 239 | void _addToLogs(dynamic obj) => _logsController.sink.add(obj); 240 | 241 | void _addToRequestLogs(ServerRequestLog data) => 242 | _requestLogsController.sink.add(data); 243 | } 244 | -------------------------------------------------------------------------------- /lib/src/server.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | import 'dart:convert'; 3 | import 'dart:io'; 4 | import 'dart:isolate'; 5 | 6 | import 'package:emodebug/emodebug.dart'; 7 | import 'package:meta/meta.dart'; 8 | import 'package:pedantic/pedantic.dart'; 9 | 10 | import 'logger.dart'; 11 | import 'models/request_log.dart'; 12 | import 'models/router.dart'; 13 | import 'request_logger.dart'; 14 | import 'types.dart'; 15 | 16 | /// The http server 17 | class IsoHttpdServer { 18 | /// Provide a [host] and a [router] 19 | IsoHttpdServer( 20 | {@required this.host, 21 | @required this.router, 22 | @required this.chan, 23 | this.apiKey, 24 | this.port = 8084, 25 | this.textDebug = false}) 26 | : assert(host != null) { 27 | log = IsoLogger(chan: chan); 28 | requestLogger = 29 | IsoRequestLogger(logChannel: _requestsLogChannel, chan: chan); 30 | if (!textDebug) { 31 | _ = const EmoDebug(deactivatePrint: true); 32 | } else { 33 | _ = const EmoDebug(deactivatePrint: true, deactivateEmojis: true); 34 | } 35 | } 36 | 37 | /// The hostname 38 | final String host; 39 | 40 | /// The server port 41 | final int port; 42 | 43 | /// The sendport to use 44 | final SendPort chan; 45 | 46 | /// The http router 47 | final IsoRouter router; 48 | 49 | /// The server api key 50 | final String apiKey; 51 | 52 | /// Disable emojis in debug 53 | final bool textDebug; 54 | 55 | /// The logger 56 | IsoLogger log; 57 | 58 | /// The requests logger 59 | IsoRequestLogger requestLogger; 60 | 61 | Stream _incomingRequests; 62 | bool _isRunning = false; 63 | bool _isInitialized = false; 64 | final _onStartedCompleter = Completer(); 65 | final _readyCompleter = Completer(); 66 | final _requestsLogChannel = StreamController.broadcast(); 67 | final _logsChannel = StreamController.broadcast(); 68 | StreamSubscription _incomingRequestsSub; 69 | HttpServer _server; 70 | EmoDebug _; 71 | 72 | /// The logs stream 73 | Stream get logs => _logsChannel.stream; 74 | 75 | /// The requests logs stream 76 | Stream get requestLogs => _requestsLogChannel.stream; 77 | 78 | /// Server is ready callback 79 | Future get onReady => _readyCompleter.future; 80 | 81 | /// Server started callback 82 | Future get onStarted => _onStartedCompleter.future; 83 | 84 | /// Is the server running 85 | bool get isRunning => _isRunning; 86 | 87 | /// The server status 88 | ServerStatus get status => _status(); 89 | 90 | /// Initialize the server 91 | void init() { 92 | log.push("Initializing server at $host:$port"); 93 | HttpServer.bind(host, port).then((HttpServer s) { 94 | _server = s; 95 | _incomingRequests = s.asBroadcastStream(); 96 | _isInitialized = true; 97 | _readyCompleter.complete(); 98 | log.push(_.init("Server initialized at $host:$port")); 99 | }); 100 | } 101 | 102 | void _unauthorized(HttpRequest request, String msg) { 103 | request.response.statusCode = HttpStatus.unauthorized; 104 | request.response.write(jsonEncode({"Status": "Unauthorized"})); 105 | request.response.close(); 106 | requestLogger.warning(msg, request); 107 | } 108 | 109 | void _notFound(HttpRequest request, String msg) { 110 | request.response.statusCode = HttpStatus.notFound; 111 | request.response.write(jsonEncode({"Status": msg})); 112 | request.response.close(); 113 | requestLogger.warning(msg, request); 114 | } 115 | 116 | /// Verify the api key 117 | bool verifyToken(HttpRequest request) { 118 | final tokenString = "Bearer $apiKey"; 119 | try { 120 | if (request.headers.value(HttpHeaders.authorizationHeader) != 121 | tokenString) { 122 | return false; 123 | } 124 | } catch (e) { 125 | log.push(_.notFound("Can not read authorization header")); 126 | return false; 127 | } 128 | return true; 129 | } 130 | 131 | /// Start the server 132 | Future start() async { 133 | assert(_isInitialized); 134 | log.push("Starting server"); 135 | if (_isRunning) { 136 | log.push(_.warning("The server is already running")); 137 | return; 138 | } 139 | _isRunning = true; 140 | //log.debug("S > start > completing"); 141 | if (!_onStartedCompleter.isCompleted) { 142 | _onStartedCompleter.complete(); 143 | } 144 | 145 | _incomingRequestsSub = _incomingRequests.listen((request) { 146 | //log.debug("REQUEST ${request.uri.path} / ${request.headers.contentType}"); 147 | // verify authorization 148 | if (apiKey != null) { 149 | final authorized = verifyToken(request); 150 | if (!authorized) { 151 | _unauthorized(request, "Unauthorized"); 152 | return; 153 | } 154 | } 155 | // check method 156 | bool isMethodAuthorized; 157 | switch (request.method) { 158 | case 'POST': 159 | isMethodAuthorized = true; 160 | break; 161 | case 'GET': 162 | isMethodAuthorized = true; 163 | break; 164 | default: 165 | isMethodAuthorized = false; 166 | } 167 | if (!isMethodAuthorized) { 168 | request.response.statusCode = HttpStatus.methodNotAllowed; 169 | request.response.close(); 170 | final msg = "Method not allowed ${request.method}"; 171 | requestLogger.warning(msg, request); 172 | return; 173 | } 174 | // find a handler 175 | IsoRequestHandler handler; 176 | IsoRequestHandler defaultHandler; 177 | var found = false; 178 | for (final route in router.routes) { 179 | if (route.path == request.uri.path) { 180 | handler = route.handler; 181 | found = true; 182 | break; 183 | } else if (route.path == "*" && defaultHandler == null) { 184 | defaultHandler = route.handler; 185 | } 186 | } 187 | if (!found) { 188 | handler = defaultHandler; 189 | } 190 | 191 | // check if a route has been found 192 | if (handler == null) { 193 | const msg = "Not found"; 194 | _notFound(request, msg); 195 | return; 196 | } 197 | // run the handler 198 | handler(request, log).then((HttpResponse response) { 199 | if (response.statusCode != HttpStatus.ok) { 200 | requestLogger.error("Status code ${response.statusCode}", request); 201 | } else if (response != null) { 202 | requestLogger.success("", request); 203 | } 204 | request.response.close(); 205 | return; 206 | }); 207 | }); 208 | } 209 | 210 | /// Stop the server 211 | bool stop() { 212 | if (_isRunning) { 213 | _incomingRequestsSub.cancel(); 214 | _isRunning = false; 215 | return true; 216 | } 217 | log.push(_.warning("The server is not running")); 218 | return false; 219 | } 220 | 221 | ServerStatus _status() { 222 | ServerStatus s; 223 | if (_isRunning == true) { 224 | s = ServerStatus.started; 225 | } else { 226 | s = ServerStatus.stopped; 227 | } 228 | return s; 229 | } 230 | 231 | /// Cleanup when finished using 232 | Future dispose() async { 233 | await _server?.close(); 234 | _server = null; 235 | unawaited(_requestsLogChannel.close()); 236 | unawaited(_logsChannel.close()); 237 | } 238 | } 239 | -------------------------------------------------------------------------------- /lib/src/types.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | import 'dart:io'; 3 | 4 | import 'logger.dart'; 5 | 6 | typedef IsoRequestHandler = Future Function( 7 | HttpRequest request, IsoLogger log); 8 | 9 | /// The server commands 10 | enum HttpdCommand { 11 | /// Start the server 12 | start, 13 | 14 | /// Stop the server 15 | stop, 16 | 17 | /// Check the server status 18 | status 19 | } 20 | 21 | /// The error types 22 | enum ServerError { 23 | /// The server is already started 24 | alreadyStarted, 25 | 26 | /// The server is not started 27 | notRunning 28 | } 29 | 30 | /// The server status 31 | enum ServerStatus { 32 | /// The server is ready 33 | ready, 34 | 35 | /// The server is started 36 | started, 37 | 38 | /// The server is stopped 39 | stopped 40 | } 41 | 42 | /// The log level 43 | enum LogMessageClass { 44 | /// Succes message 45 | success, 46 | 47 | /// Error message 48 | error, 49 | 50 | /// Warning message 51 | warning 52 | } 53 | 54 | /// The request log type 55 | enum IsoLogType { 56 | /// Debug level 57 | debug, 58 | 59 | /// Info level 60 | info, 61 | 62 | /// Warning level 63 | warning, 64 | 65 | /// Error level 66 | error, 67 | } 68 | -------------------------------------------------------------------------------- /lib/src/utils.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:io'; 3 | 4 | import 'package:body_parser/body_parser.dart'; 5 | import 'package:path/path.dart' as p; 6 | 7 | /// A json response builder 8 | Future jsonResponse(HttpRequest request, dynamic data) async { 9 | request.response.statusCode = HttpStatus.ok; 10 | request.response.headers.contentType = 11 | ContentType("application", "json", charset: "utf-8"); 12 | request.response.write(jsonEncode(data)); 13 | return request.response; 14 | } 15 | 16 | /// Decode post requests 17 | Future decodeMultipartRequest(HttpRequest request) async => 18 | // ignore: deprecated_member_use 19 | parseBody(request); 20 | 21 | /// A convenience function to list a directory 22 | Future>>> directoryListing( 23 | Directory dir) async { 24 | final contents = dir.listSync()..sort((a, b) => a.path.compareTo(b.path)); 25 | final dirs = >[]; 26 | final files = >[]; 27 | for (final fileOrDir in contents) { 28 | if (fileOrDir is Directory) { 29 | final dir = Directory("${fileOrDir.path}"); 30 | dirs.add({ 31 | "name": p.basename(dir.path), 32 | }); 33 | } else { 34 | final file = File("${fileOrDir.path}"); 35 | files.add({ 36 | "name": p.basename(file.path), 37 | "size": file.lengthSync() 38 | }); 39 | } 40 | } 41 | return {"files": files, "directories": dirs}; 42 | } 43 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: isohttpd 2 | description: A lightweight http server that runs in an isolate. Router and logs are included. 3 | version: 0.5.0 4 | homepage: https://github.com/synw/isohttpd 5 | 6 | environment: 7 | sdk: ">=2.2.0 <3.0.0" 8 | 9 | dev_dependencies: 10 | test: ^1.6.5 11 | 12 | dependencies: 13 | pedantic: ^1.9.2 14 | extra_pedantic: ^1.2.0 15 | meta: ^1.2.4 16 | body_parser: ^1.1.1 17 | iso: ^0.3.0 18 | path: ^1.7.0 19 | emodebug: ^0.5.0 20 | --------------------------------------------------------------------------------