dia
a simple dart http server like koajs.
this package allows you to create a http / http server in a couple of lines. dia creates a context from a bunch of request and response and passes it through the middleware.
the main idea of the project is minimalism. the package contains only basic functionality, everything else is implemented in separate packages. this allows you to keep the project code clean and connect only those dependencies that are really needed in it.
install:
add to pubspec.yaml in dependencies section this:
dia: ^0.1.3
then run pub get
usage:
a simple usage example:
import 'package:dia/dia.dart';
main() {
final app = app();
app.use((ctx,next) async {
ctx.body = 'hello world!';
});
app
.listen('localhost', 8080)
.then((info) => print('server started on http://localhost:8080'));
}
context contain getters and setters for httprequest
fields: response, response.headers, response.headers.contenttype, response.statuscode, that allow use it easy.
context contain method throwerror
that allow easy return http errors by statuscode.
example throwerror
:
app.use((ctx,next) async {
ctx.throwerror(401);
});
you can use custom context
with additional fields and methods. in this case, you need to inherit from the base context and pass the instance of context creation function to the app constructor.
/// create custom context class
class customcontext extends context{
string? additionalfield;
customcontext(httprequest request) : super(request);
}
void main() {
/// create dia instance
final app = app((request) => customcontext(request));
/// add additionalfield value
app.use((ctx, next) async {
ctx.additionalfield = 'additional value';
await next();
});
/// final middleware to response
app.use((ctx, next) async {
ctx.contenttype = contenttype.text;
ctx.body = ctx.additionalfield;
});
/// start server listen on localhost:8080
app
.listen('localhost', 8080)
.then((info) => print('server started on http://localhost:8080'));
}
your can add handler to all http errors:
app.use((ctx,next) async {
await next();
if(ctx.statuscode!=200){
//....
}
});
you can start your server with ssl:
const serverkey = 'cert/key.pem';
const certificatechain = 'cert/chain.pem';
final servercontext = securitycontext();
servercontext
.usecertificatechainbytes(await file(certificatechain).readasbytes());
servercontext.useprivatekey(serverkey, password: 'password');
app.listen('localhost', 8444, securitycontext: servercontext);
for more details, please, see example and test folder.
Comments are closed.