Created
December 30, 2019 13:54
-
-
Save kjelly/1e8145e78be1b6c419db1c4c1a9b4b1e to your computer and use it in GitHub Desktop.
Simple Web Server Sample Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:io'; | |
import 'dart:convert'; | |
import 'package:http_server/http_server.dart'; | |
class Router { | |
void Function(HttpRequest, List<String>, HttpResponse) noRoute; | |
Router({this.noRoute = null}) {} | |
Map<String, void Function(HttpRequest, List<String>, HttpResponse)> handles = | |
{}; | |
Map<String, RegExp> regex = {}; | |
bool addRouter(String pattern, | |
void Function(HttpRequest, List<String>, HttpResponse) handle) { | |
handles[pattern] = handle; | |
regex[pattern] = RegExp(pattern); | |
return true; | |
} | |
void serve(HttpRequest req) async { | |
for (var i in handles.keys) { | |
var r = regex[i]; | |
var match = r.firstMatch(req.uri.path); | |
if (match != null) { | |
try { | |
await handles[i]( | |
req, | |
match.groups(List.generate(match.groupCount + 1, (i) => i)), | |
req.response); | |
await req.response.close(); | |
} catch (e) { | |
print(e.toString()); | |
} | |
return; | |
} | |
} | |
if (noRoute != null) { | |
noRoute(req, null, req.response); | |
} else { | |
await req.response.writeln("Route not found."); | |
await req.response.close(); | |
} | |
} | |
} | |
Future main() async { | |
var staticFiles = VirtualDirectory('.'); | |
staticFiles.allowDirectoryListing = true; /*1*/ | |
var server; | |
try { | |
server = await HttpServer.bind(InternetAddress.loopbackIPv4, 4044); | |
} catch (e) { | |
print("Couldn't bind to port 4044: $e"); | |
exit(-1); | |
} | |
var r = Router(); | |
r | |
..addRouter('cats/', (req, args, resp) { | |
resp.writeln(jsonEncode({ | |
"objs": ["cat1", "cat2", "cat3"] | |
})); | |
}) | |
..addRouter('cat/(\\d)+/', (req, args, resp) { | |
resp.writeln(jsonEncode({"name": "cat" + args[1]})); | |
}) | |
..addRouter('web/.*', (req, args, resp) async { | |
await staticFiles.serveRequest(req); | |
}); | |
await for (HttpRequest req in server) { | |
r.serve(req); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment