Skip to content

Commit

Permalink
add examples
Browse files Browse the repository at this point in the history
  • Loading branch information
KOBA789 committed Oct 28, 2016
1 parent 7db7220 commit 665e657
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
1 change: 1 addition & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ circle.yml
.babelrc
.gitignore
/coverage.lcov
/examples/
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,42 @@
[![Codecov](https://img.shields.io/codecov/c/github/KOBA789/dfa-router.svg?style=flat-square)](https://codecov.io/gh/KOBA789/dfa-router)

A simple server-side url router using Deterministic Finite Automaton.

## How to Use

It behaves like a simple key-value map.

```
const router = new Router();
router.add('GET', '/foo', 'foo');
router.add('GET', '/bar', 'bar');
const foo = router.route('GET', '/foo');
assert.deepEqual(foo, {
type: 'found',
value: 'foo',
params: {},
});
const bar = router.route('GET', '/bar');
assert.deepEqual(bar, {
type: 'found',
value: 'bar',
params: {},
});
```

And also, it can capture parameters.

```
const router = new Router();
router.add('GET', '/:param', 'foo');
const foo = router.route('GET', '/value');
assert.deepEqual(foo, {
type: 'found',
value: 'foo',
params: { param: 'value' },
});
```

See `examples/server.js` and `test/` to learn more.
39 changes: 39 additions & 0 deletions examples/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const http = require('http');
const url = require('url');

const Router = require('../');

const router = new Router();
router.add('GET', '/', (req, res, params) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('root');
});

router.add('POST', '/post', (req, res, params) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('/post');
});

const app = http.createServer((req, res) => {
const urlObj = url.parse(req.url);
const result = router.route(req.method, urlObj.pathname, true);
switch (result.type) {
case 'found':
result.value(req, res, Object.assign({}, urlObj.query, result.params));
break;
case 'not_found':
res.writeHead(404);
res.end();
break;
case 'method_not_allowed':
res.writeHead(405);
res.end(`Allowed methods are: ${result.allowed.join(', ')}`);
break;
}
});

const PORT = process.env.PORT || 8124;
const HOSTNAME = process.env.HOSTNAME || '127.0.0.1';
app.listen(PORT, HOSTNAME, () => {
console.log(`Server running at http://${HOSTNAME}:${PORT}/`);
});

0 comments on commit 665e657

Please sign in to comment.