So, you know express.js
or fastify
or Koa.js
? Cool, but what if your primary language is dart
? You gonna learn Node.js just for that?!
No right. I thought so.
So, what are we waiting for ? Let's get started for web servers in dart.
First of all, install the official shelf
dependency.
dependencies:
shelf: ^1.2.0 # Prefer latest please !
Then, let's jump into the codes...
import 'dart:async';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
Future<Response> manageRequests(Request request) async {
print('[Debug] ${request.method} ${request.requestedUri.normalizePath().path}');
switch (request.requestedUri.normalizePath().path) {
case '/':
return Response.ok(
File('app/index.html').readAsStringSync(),
headers: {
'Content-Type': 'text/html',
}
);
case '/index.html':
return Response.ok(
File('app/index.html').readAsStringSync(),
headers: {
'Content-Type': 'text/html',
}
);
case '/tailwind.css':
return Response.ok(
File('app/tailwind.css').readAsStringSync(),
headers: {
'Content-Type': 'text/css',
}
);
case '/script.js':
return Response.ok(
File('app/script.js').readAsStringSync(),
headers: {
'Content-Type': 'text/javascript',
}
);
default:
return Response.notFound('Not found');
}
}
Future<void> serve() async {
FutureOr<Response> Function(Request) handler = Pipeline().addHandler(manageRequests);
try {
HttpServer server = await shelf_io.serve(handler, 'localhost', 1134);
print('[Info] Serving at http://${server.address.host}:${server.port} !');
} catch (error) {
print('[Warning] Port 1134 is already in use.');
exit(0);
}
}
void main(List<String>? args) async {
await serve();
}
This will start the WebServer at the port 1134
.
Now Ofc there exists multiple libraries on pub.dev like express.js
implemented in dart (with less features) but trust me, you seriously don't wanna get into those, this is the best way of making WebServers in Dart
. More like fastest and easiest way in dart.
- Guess what, This works in Flutter too...
Top comments (0)