Skip to content

Instantly share code, notes, and snippets.

@kjelly
Created December 30, 2019 13:54
Show Gist options
  • Save kjelly/1e8145e78be1b6c419db1c4c1a9b4b1e to your computer and use it in GitHub Desktop.
Save kjelly/1e8145e78be1b6c419db1c4c1a9b4b1e to your computer and use it in GitHub Desktop.
Simple Web Server Sample Code
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