XUtils

Start

Sinatra inspired web framework to serve static files, handle dynamic requests, websockets and create JSON responses.


Start

Sinatra inspired web framework.

It has simple API to serve static files, handle dynamic requests, websockets and create JSON responses.

import 'package:start/start.dart';

void main() {
  start(port: 3000).then((Server app) {

    app.static('web');

    app.get('/hello/:name.:lastname?').listen((request) {
      request.response
        .header('Content-Type', 'text/html; charset=UTF-8')
        .send('Hello, ${request.param('name')} ${request.param('lastname')}');
    });

    app.ws('/socket').listen((socket) {
      socket.on('ping').listen((data) => socket.send('pong'));
      socket.on('pong').listen((data) => socket.close(1000, 'requested'));
    });

  });
}

API

start()

You start the server with start() function. It has 3 named arguments and returns Server future

start({String host: '127.0.0.1', int port: 80})

Server

listen(host, port) // start the server (it's performed by the start function)
stop() // stops the server
get|post|put|delete(String route) // adds a handler, returns a Stream<Request>
ws(String route) // adds WebSocket handler, returns a Stream
static(String path, {bool jail, bool listing, bool links}) // serves static files from `path`, follows symlinks outside the root if jail is false

Routes

Route is a string with placeholders like :firstname its value is available through the Request param() method. Placeholders should start with colon :, if placeholder ends with a question mark ? it’s optional. "/hello/:firstname.:lastname?" will match "/hello/john" and "/hello/john.doe"

Request

header(String name) // get header
accepts(String type) // check accept header
input // raw HttpRequest stream
path // requested URI path
uri // requested URI
cookies // provided cookies
param(String name) // get query param by name
payload(Encoding enc) // get a promise with a Map of request body params

Response

header(String name, [value]) // get or set header
get(String name) // get header
set(String name) // set header
type(contentType) // set Content-Type
cache(String cacheType) // set Cache-Control
status(code) // sets response status code
cookie(name, val) // sets cookie
add(string) // add a string to response
close() // closes response
send(string) // sends string and closes response
json(Map data) // stringifies map and sends it
jsonp(String name, Map data) // stringifies map and sends it in callback as `name(data)`
render(viewName, [Map params]) // renders server view

Socket

send(message) // sends message
on(message, action) // adds handler to message
close(status, reason) // closes socket

Articles

  • coming soon...