GithubHelp home page GithubHelp logo

synth's Introduction

synth!

synth

Simple, minimal, and efficient Dart web developement framework.

Prerequisite: Dart and Git installed in your machine.

Basic usage

Step 1: Create a project using Dart IDE or commandline. Instructions below is thru commandline.

$ mkdir hello
$ cd hello

Step 2: Inside hello directory create a pubspec.yaml file with the contents below.

name: hello
dependencies:
  synth:
    git: git://github.com/maiah/synth.git

Step 3: Inside hello directory execute pub install. This will create packages folder and download the synth library.

$ pub install

Step 4: Create hello_server.dart file inside hello folder and import synth.dart library in that file.

import 'package:synth/synth.dart';

Step 5: And also in this file create main method and define your routes and start the HTTP server.

main () {
  route('GET', '/', (req, res)
    => res.write('Hello, World!'));

  start(port: 7000);
  print('Listening on port 7000');
}

Step 6: Run your Dart program using Dart IDE or commandline. Instructions below is thru commandline.

$ dart hello_server.dart

Step 7: Open your web browser and go to http://localhost:7000 and the message below will be shown.

Hello, World!

Routing

You can register a route with a path that holds a variable like below.

route('GET', '/person/:name', (req, res)
  => res.write('Hi there.'));

Then you can access this route with http://localhost:7000/person/maiah URL.

You can also have multiple variable in a single route path.

route('GET', '/person/:name/department/:id', (req, res)
  => res.write('Hello there.'));

Then you can access this route with http://localhost:7000/person/maiah/department/557 URL.

Adding middleware

Adding middleware is very simple. It's like providing a HTTP request handler. But you have to register your middleware thru the use method.

Unlike request handler, middlewares has a 3rd parameter next that can be executed to call the next middleware in the stack. Take a look at the typedef Middleware signature below:

typedef void Middleware(Request req, Response res, next);

For example you want to add a middleware that will log the request path each time a request is processed.

use((req, res, next) {
  print('Request path is ${req.path}');
  next(); // Executes the next middleware in the stack if any.
});

The code above will register the middleware closure you created and will execute everytime a request is processed.

Adding middleware into a specific route

Adding middleware into a specific route is done thru route method. The middleware method signature is the same. Add it before the request handler like below.

...
var someMiddleware = (req, res, next) {
  print('Some middleware here.');
  next();
}
...

route('GET', '/', someMiddleware, (req, res) {
  res.write('A route with middleware.');
});

The code above will register and execute the middleware only for this specific route.

Built-in middlewares

  • logPath - Used for logging the request path and its query parameters.
  • reqContent - Used to gather request POST data and populate Request#dataMap property which can be accessed by user-defined request handlers and other middlewares.
  • reqJsonContent - Similar to reqContent, except it parses JSON POST data and populates Request#dataObj.

Synth Robot Boy art by KabisCube [email protected]

synth's People

Contributors

maiah avatar sqs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

synth's Issues

Route-specific Middleware

Provide a way to add a middleware on a specific route. The code is something like below.

...
void myMiddleware(req, res, next) {
  ...
}
...

route('GET', '/', myMiddleware, (req, res)
    => res.write('Hello, World!'));

Error on pageload

When I am using your example setup and try to run it with the latest sdk at revision 14458 or revision 14167 I receive following error when I visit http://localhost:7000

Unhandled exception:
NoSuchMethodError : method not found: 'call'
Receiver: Array
Arguments: []
#0      _HttpServer.listenOn.onConnection.<anonymous closure> (dart:io:3151:11)
#1      _HttpConnection._onConnectionClosed (dart:io:3062:14)
#2      _HttpConnectionBase._onError (dart:io:3010:24)
#3      _HttpConnection._HttpConnection.<anonymous closure> (dart:io:3058:40)
#4      _HttpParser.writeList (dart:io:4332:14)
#5      _HttpConnectionBase._onData._onData (dart:io:2991:41)
#6      _SocketBase._multiplex (dart:io-patch:399:26)
#7      _SocketBase._sendToEventHandler.<anonymous closure> (dart:io-patch:500:20)
#8      _ReceivePortImpl._handleMessage (dart:isolate-patch:37:92)

This works on revision 13851.

I tried to debug this but couldn't get to the bottom of it. Not sure if this is a language bug or a bug in the framework.

Any help would be greatly appreciated.

Matt

Using futures in routes causes issues when doing async write to response stream

Long story short. I have routes that does some database lookup with an API based on Futures.

Then problem is, that the lines 102-107 in ehttp.dart makes it impossible to do this since the outputStream is being closed as soon as the inputstream is.

synthReq.inputStream.onClosed = () {
        // Close response stream if needed.
        if (!synthRes.outputStream.closed) {
          synthRes.outputStream.close();
        }
      };

Perhaps I'm doing something wrong.

Removing these lines does make it work but it has a sideeffect in my middlewares.

Enhanced request object

Create an enhanced HTTP request object that can be used by request handlers and middlewares.

Response redirect

Provide a redirect method to Response object that can be used by middlewares and user request-handlers.

Proposed usage:

res.redirect('/some/path/here');

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.