lucifer lightbringer
lucifer is a fast, light-weight web framework in dart.
it’s built on top of native httpserver
to provide a simple way to fulfill the needs of many modern web server this day.
lucifer is open, efficient, and has lots of built in features to perform dozen kinds of things.
installation
you can start create a new project with lucy command.
$ dart pub global activate lucy
$ lucy create desire
the first command will activate lucifer command-line interface (cli), named lucy, to be accessible in your terminal. and then lucy create desire
creates a new project named desire
in the desire
directory.
feel free to use any project name you want.
starting
now we are ready to build our web server.
open file main.dart
in your project bin
directory and see the structure of a simple lucifer application.
import 'package:lucifer/lucifer.dart';
void main() {
final app = app();
final port = env('port') ?? 3000;
app.use(logger());
app.get('/', (req req, res res) async {
await res.send('hello detective');
});
await app.listen(port);
print('server running at http://${app.host}:${app.port}');
app.checkroutes();
}
test running it with command.
$ cd desire
$ lucy run
and open url http://localhost:3000
in your browser.
if all went well, it will display hello detective
and print this message in your terminal.
server running at http://localhost:3000
fundamentals
we can learn the basic of lucifer by understanding the main.dart
code that’s generated by lucy create
command.
import 'package:lucifer/lucifer.dart';
void main() async {
final app = app();
final port = env('port') ?? 3000;
app.use(logger());
app.get('/', (req req, res res) async {
await res.send('hello detective');
});
await app.listen(port);
print('server running at http://${app.host}:${app.port}');
app.checkroutes();
}
those short lines of code do several things behind the scene.
first, we import lucifer
and create a web application by assigning a new app
object to app
import 'package:lucifer/lucifer.dart';
final app = app();
then we set the server port to 3000
from .env
file that’s located in your root project directory.
feel free to change with any port number you want.
final port = env('port') ?? 3000;
once we have the app
object, we tell it to listen to a get request on path /
by using app.get()
app.get('/', (req req, res res) async {
});
every http verbs has its own methods in lucifer: get()
, post()
, put()
, delete()
, patch()
with the first argument corresponds to the route path.
app.get('/', (req req, res res) {
});
app.post('/', (req req, res res) {
});
app.put('/', (req req, res res) {
});
app.delete('/', (req req, res res) {
});
app.patch('/', (req req, res res) {
});
next to it, we can see a callback function that will be called when an incoming request is processed, and send a response with it.
to handle the incoming request and send a response, we can write our code inside.
app.get('/', (req req, res res) async {
await res.send('hello detective');
});
lucifer provides two objects, req
and res
, that represents req
and res
instance.
req
is an http request built on top of native httprequest
. it holds all information about the incoming request, such as request parameters, query string, headers, body, and much more.
res
is an http response built on top of native httpresponse
. it’s mostly used for manipulating response to be sent to the client.
what we did before is sending a message string hello detective
to the client using res.send()
. this method sets the string in the response body, and then close the connection.
the last line of our code starts the server and listen to the incoming requests on the specified port
await app.listen(port);
print('server running at http://${app.host}:${app.port}');
alternatively, we can use app.listen()
as follows.
await app.listen(port, '127.0.0.1');
await app.listen(port, () {
print('server running at http://${app.host}:${app.port}');
});
await app.listen(port, 'localhost', () {
print('server running at http://${app.host}:${app.port}');
});
environment variables
environment is some set of variables known to a process (such as, env, port, etc). it’s recommended to mimic production environment during development by reading it from .env
file.
when we use lucy create
command, a .env
file is created in the root project directory that contains these default values.
env = development
port = 3000
then it’s called from the dart code using env()
method.
void main() {
final app = app();
final port = env('port') ?? 3000; // get port from env
// get env to check if it's in a development or production stage
final environment = env('env');
...
}
for our own security, we should use environment variables for important things, such as database configurations and json web token (jwt) secret.
and one more thing, if you open .gitignore
file in the root directory, you can see .env
is included there. it means our .env
file will not be uploaded to remote repository like github, and the values inside will never be exposed to the pubic.
request parameters
a simple reference to all the request object properties and how to use them.
we’ve learned before that the req
object holds the http request informations. there are some properties of req
that you will likely access in your application.
property | description |
---|---|
app | holds reference to the lucifer app object |
uristring | uri string of the request |
path | the url path |
method | the http method being used |
params | the route named parameters |
query | a map object containing all the query string used in the request |
body | contains the data submitted in the request body (must be parsed before you can access it) |
cookies | contains the cookies sent by the request (needs the `cookieparser` middleware) |
protocol | the request protocol (http or https) |
secure | true if request is secure (using https) |
get query string
now we’ll see how to retrieve the get query parameters.
query string is the part that comes after url path, and starts with a question mark ?
like ?username=lucifer
.
multiple query parameters can be added with character &
.
?username=lucifer&age=10000
how can we get those values?
lucifer provides a req.query
object to make it easy to get those query values.
app.get('/', (req req, res res) {
print(req.query);
});
this object contains map of each query parameter.
if there are no query, it will be an empty map or {}
.
we can easily iterate on it with for loop. this will print each query key and its value.
for (var key in req.query.keys) {
var value = req.query[key];
print('query $key: $value');
}
or you can access the value directly with res.q()
req.q('username'); // same as req.query['username']
req.q('age'); // same as req.query['age']
post request data
post request data are sent by http clients, such as from html form, or from a post request using postman or from javascript code.
how can we access these data?
if it’s sent as json with content-type: application/json
, we need to use json()
middleware.
final app = app();
// use json middleware to parse json request body
// usually sent from rest api
app.use(json());
// use xssclean to clean the inputs
app.use(xssclean());
if it’s sent as urlencoded content-type: application/x-www-form-urlencoded
, use urlencoded()
middleware.
final app = app();
// use urlencoded middleware to parse urlencoded request body
// usually sent from html form
app.use(urlencoded());
// use xssclean to clean the inputs
app.use(xssclean());
now we can access the data from req.body
app.post('/login', (req req, res res) {
final username = req.body['username'];
final password = req.body['password'];
});
or simply use req.data()
app.post('/login', (req req, res res) {
final username = req.data('username');
final password = req.data('password');
});
besides json()
and urlencoded()
, there are other available built in body parsers we can use.
raw()
: to get request body as raw bytestext()
: to get request body as a plain stringjson()
: to parse json request bodyurlencoded()
: to parse urlencoded request bodymultipart()
: to parse multipart request body
to ensure the core framework stays lightweight, lucifer will not assume anything about your request body. so you can choose and apply the appropriate parser as needed in your application.
however, if you want to be safe and need to be able to handle all forms of request body, simply use the bodyparser()
middleware.
final app = app();
app.use(bodyparser());
it will automatically detect the type of request body, and use the appropriate parser accordingly for each incoming request.
send response
in the example above, we’ve used res.send()
to send a simple response to the client.
app.get('/', (req req, res res) async {
await res.send('hello detective');
});
if you pass a string, lucifer will set content-type
header to text/html
.
if you pass a map or list object, it will set as application/json
, and encode the data into json.
res.send()
sets the correct content-length
response header automatically.
res.send()
also close the connection when it’s all done.
you can use res.end()
method to send an empty response without any content in the response body.
app.get('/', (req req, res res) async {
await res.end();
});
another thing is you can send the data directly without res.send()
app.get('/string', (req, res) => 'string');
app.get('/int', (req, res) => 25);
app.get('/double', (req, res) => 3.14);
app.get('/json', (req, res) => { 'name': 'lucifer' });
app.get('/list', (req, res) => ['lucifer', 'detective']);
http status response
you can set http status response using res.status()
method.
res.status(404).end();
or
res.status(404).send('not found');
or simply use res.sendstatus()
// shortcut for res.status(200).send('ok');
res.sendstatus(200);
// shortcut for res.status(403).send('forbidden');
res.sendstatus(403);
// shortcut for res.status(404).send('not found');
res.sendstatus(404);
// shortcut for res.status(500).send('internal server error');
res.sendstatus(500);
json response
besides res.send()
method we’ve used before, we can use res.json()
to send json data to the client.
it accepts a map or list object, and automatically encode it into json string with jsonencode()
res.json({ 'name': 'lucifer', 'age': 10000 });
res.json(['lucifer', 'detective', 'amenadiel']);
cookies
use res.cookie()
to manage cookies in your application.
res.cookie('username', 'lucifer');
this method accepts additional parameters with various options.
res.cookie(
'username',
'lucifer',
domain: '.luciferinheaven.com',
path: '/admin',
secure: true,
);
res.cookie(
'username',
'lucifer',
expires: duration(milliseconds: datetime.now().millisecondssinceepoch + 900000),
httponly: true,
);
here is some cookie parameters you can eat.
value | type | description |
---|---|---|
domain | string | domain name for the cookie. defaults to the domain name of the app |
expires | date | expiry date of the cookie in gmt. if not specified or set to 0, creates a session cookie that will be deleted when client close the browser. |
httponly | bool | flags the cookie to be accessible only by the web server |
maxage | int | convenient option for setting the expiry time relative to the current time in milliseconds |
path | string | path for the cookie. defaults to / |
secure | bool | marks the cookie to be used with https only |
signed | bool | indicates if the cookie should be signed |
samesite | bool or string | set the value of samesite cookie |
a cookie can be deleted with
res.clearcookie('username');
or to clear all cookies.
res.clearcookies();
secure cookies
you can secure cookies in your application using securecookie()
middleware.
string cookiesecret = env('cookie_secret_key');
app.use(securecookie(cookiesecret));
cookie_secret_key
needs to be set in the .env
file and should be a random string unique to your application.
http headers
we can get http header of a request from req.headers
app.get('/', (req, res) {
print(req.headers);
});
or we use req.get()
to get an individual header value.
app.get('/', (req, res) {
final useragent = req.get('user-agent');
// same as
req.header('user-agent');
});
to change http header of a response to the client, we can use res.set()
and res.header()
res.set('content-type', 'text/html');
// same as
res.header('content-type', 'text/html');
there are other ways to handle the content-type header.
res.type('.html'); // res.set('content-type', 'text/html');
res.type('html'); // res.set('content-type', 'text/html');
res.type('json'); // res.set('content-type', 'application/json');
res.type('application/json'); // res.set('content-type', 'application/json');
res.type('png'); // res.set('content-type', 'image/png');
redirects
using redirects are common thing to do in a web application. you can redirect a response in your application with res.redirect()
or res.to()
res.redirect('/get-over-here');
// same as
res.to('/get-over-here');
this will create redirect with a default 302 status code.
we can also use it this way.
res.redirect(301, '/get-over-here');
// same as
res.to(301, '/get-over-here');
you can pass the path with an absolute path (/get-over-here
), an absolute url (https://scorpio.com/get-over-here
), a relative path (get-over-here
), or ..
to go back one level.
res.redirect('../get-over-here');
res.redirect('..');
or simply use res.back()
to redirect back to the previous url based on the http referer value sent by client in the request header (defaults to / if not set).
res.back();
routing
routing is the process of determining what should happen when a url is called, and which parts of the application needs to handle the request.
in the example before we’ve used.
app.get('/', (req, res) async {
});
this creates a route that maps root path /
with http get method to the response we provide inside the callback function.
we can use named parameters to listen for custom request.
say we want to provide a profile api that accepts a string as username, and return the user details. we want the string parameter to be part of the url (not as query string).
so we use named parameters like this.
app.get('/profile/:username', (req req, res res) {
// get username from url parameter
final username = req.params['username'];
print(username);
});
you can use multiple parameters in the same url, and it will automatically added to req.params
values.
as an alternative, you can use req.param()
to access an individual value of req.params
app.get('/profile/:username', (req req, res res) {
// get username from url parameter
final username = req.param('username');
print(username);
});
advanced routing
we can use router
object from app.router()
to build an organized routing.
final app = app();
final router = app.router();
router.get('/login', (req, res) async {
await res.send('login page');
});
app.use('/auth', router);
now the login page will be available at http://localhost:3000/auth/login.
you can register more than one routers in your app.
final app = app();
final auth = app.router();
final user = app.router();
// register routes for auth
auth.get('/login', (req req, res res) async {
await res.send('login page');
});
auth.post('/login', (req req, res res) async {
// process post login
});
auth.get('/logout', (req req, res res) async {
// process logout
});
// register routes for user
user.get('/', (req req, res res) async {
await res.send('list user');
});
user.get('/:id', (req req, res res) async {
final id = req.param('id');
await res.send('profile $id');
});
user.post('/', (req req, res res) async {
// create user
});
user.put('/:id', (req req, res res) async {
// edit user by id
});
user.delete('/', (req req, res res) async {
// delete all users
});
user.delete(':id', (req req, res res) async {
// delete user
});
// apply the router
app.use('/auth', auth);
app.use('/user', user);
using app.router()
is a good practice to organize your endpoints. you can split them into independent files to maintain a clean, structured and easy-to-read code.
another way to organize your app is using app.route()
final app = app();
app.route('/user')
.get('/', (req req, res res) async {
await res.send('list user');
})
.get('/:id', (req req, res res) async {
final id = req.param('id');
await res.send('profile $id');
})
.post('/', (req req, res res) async {
// create user
})
.put('/:id', (req req, res res) async {
// edit user by id
})
.delete('/', (req req, res res) async {
// delete all users
})
.delete('/:id', (req req, res res) async {
// delete user
});
with this app.route()
you can also use controller
. this is especially useful when you’re building a rest api.
lets create a new controller in the controller
directory.
class usercontroller extends controller {
usercontroller(app app) : super(app);
@override
futureor index(req req, res res) async {
await res.send('user list');
}
@override
futureor view(req req, res res) async {
await res.send('user detail');
}
@override
futureor create(req req, res res) async {
await res.send('create user');
}
@override
futureor edit(req req, res res) async {
await res.send('edit user');
}
@override
futureor delete(req req, res res) async {
await res.send('delete user');
}
@override
futureor deleteall(req req, res res) async {
await res.send('delete all users');
}
}
then use it in your main app like this.
final app = app();
final user = usercontroller(app);
// this will add all associated routes for all methods
app.route('/user', user);
// the 1-line code above is the same as
// manually adding these yourself
app.route('/user')
.get('/', user.index)
.post('/', user.create)
.delete('/', user.deleteall)
.get('/:id', user.view)
.put('/:id', user.edit)
.delete('/:id', user.delete);
it’s good practice to split your routes into its own independent controllers.
also, feel free to add more methods to your controller
class usercontroller extends controller {
...
futureor vip(req req, res res) async {
await res.send('list of vip users');
}
}
then apply the method by chaining app.route()
final app = app();
final user = usercontroller(app);
// this will add route get /user/vip into your app
// along with all the standard routes above
app.route('/user', user).get('/vip', user.vip);
to help you with adding controller
to your project, lucifer provides another command like this.
$ lucy c post
these command will create a post_controller.dart
file in the /bin/controller
directory, and automatically fill it with a boilerplate postcontroller
class.
you can use it to create more than one controller
like this.
$ lucy c post news user customer
static files
it’s common to have images, css, and javascripts in a public folder, and expose them.
you can do it by using static()
middleware.
final app = app();
app.use(static('public'));
now if you have index.html
file in the public
directory, it will be served automatically when you hit http://localhost:3000
.
sending files
lucifer provides a simple way to send file as an attachment to the client with res.download()
when user hit a route that sends file with this method, browsers will prompt the user for download. instead of showing it in a browser, it will be saved into local disk.
app.get('/downloadfile', (req req, res res) async {
await res.download('thefile.pdf');
// same as
await res.sendfile('thefile.pdf');
});
you can send a file with a custom filename.
app.get('/downloadfile', (req req, res res) async {
await res.download('thefile.pdf', 'file.pdf');
});
and to handle the error when sending file, use this.
app.get('/downloadfile', (req req, res res) async {
final err = await res.download('./thefile.pdf', 'file.pdf');
if (err != null) {
// handle error
}
});
cors
a client app running in the browser usually can access only the resources from the same domain (origin) as the server.
loading images or scripts/styles usually works, but xhr and fetch calls to another server will fail, unless the server implements a way to allow that connection.
that way is cors (cross-origin resource sharing).
loading web fonts using @font-face
also has same-origin-policy by default, and also other less popular things (like webgl textures).
if you don’t set up a cors policy that allows 3rd party origins, their requests will fail.
a cross origin request fail if it’s sent
- to a different domain
- to a different subdomain
- to a different port
- to a different protocol
and it’s there for your own security, to prevent any malicious users from exploiting your resources.
but if you control both the server and the client, you have good reasons to allow them to talk with each other.
use cors
middleware to set up the cors policy.
as example, lets say you have a simple route without cors.
final app = app();
app.get('/no-cors', (req req, res res) async {
await res.send('risky without cors');
});
if you hit /no-cors
using fetch request from a different origin, it will raise a cors issue.
all you need to make it work is using the built in cors
middleware and pass it to the request handler.
final app = app();
app.get('/yes-cors', cors(), (req req, res res) async {
await res.send('now it works');
});
you can apply cors
for all incoming requests by using app.use()
final app = app();
app.use(cors());
app.get('/', (req req, res res) async {
await res.send('now all routes will use cors');
});
by default, cors will set cross-origin header to accept any incoming requests. you can change it to only allow one origin and block all the others.
final app = app();
app.use(cors(
origin: 'https://luciferinheaven.com'
));
app.get('/', (req req, res res) async {
await res.send('now all routes can only accept request from https://luciferinheaven.com');
});
you can also set it up to allow multiple origins.
final app = app();
app.use(cors(
origin: [
'https://yourfirstdomain.com',
'https://yourseconddomain.com',
],
));
app.get('/', (req req, res res) async {
await res.send('now all routes can accept request from both origins');
});
session
we need to use sessions to identify client across many requests.
by default, web requests are stateless, sequential and two requests can’t be linked to each other. there is no way to know if a request comes from a client that has already performed another request before.
users can’t be identified unless we use some kind of magic that makes it possible.
this is what sessions are (json web token is another).
when handled correctly, each user of your application or your api will be assigned to a unique session id, and it allows you to store the user state.
we can use built in session
middleware in lucifer.
final app = app();
app.use(session(secret: 'super-s3cr3t-key'));
and now all requests in your app will use session.
secret
is the only required parameter, but there are many more you can use. secret
should use a random string, unique to your application. or use a generated string from randomkeygen.
this session is now active and attached to the request. and you can access it from req.session()
app.get('/', (req req, res res) {
print(req.session()); // print all session values
});
to get a specific value from the session, you can use req.session(name)
final username = req.session('username');
or use req.session(name, value)
to add (or replace) value in the session.
final username = 'lucifer';
req.session('username', username);
sessions can be used to to communicate data between middlewares, or to retrieve it later on the next request.
where do we store this session?
well, it depends on the set up that we use for our sessions.
it can be stored in
- memory: this is the default, but don’t use it in production
- database: like postgres, sqlite, mysql or mongodb
- memory cache: like redis or memcached
all the session store above will only set session id in a cookie, and keep the real data server-side.
clients will receive this session id, and send it back with each of their next http requests. then the server can use it to get the store data associated with these session.
memory is the default setting for session, it’s pretty simple and requires zero setup on your part. however, it’s not recommended for production.
the most efficient is using memory cache like redis, but it needs some more efforts on your part to set up the infrastructure.
json web token
json web token (jwt) is an open standard (rfc 7519) that defines a compact and self-contained way for securely transmitting information between parties as a json object.
this information can be verified and trusted because it is digitally signed. jwts can be signed using a secret (with the hmac algorithm) or a public/private key pair using rsa or ecdsa.
you can use jwt feature in lucifer by using an instance of jwt
to sign and verify token. remember to put the jwt secret in environment variables.
final app = app();
final port = env('port') ?? 3000;
final jwt = jwt();
final secret = env('jwt_secret');
app.get('/login', (req req, res res) {
...
final payload = <string, dynamic>{
'username': 'lucifer',
'age': 10000,
};
final token = jwt.sign(
payload,
secret,
expiresin: duration(seconds: 86400),
);
// send token to the client by putting it
// into 'x-access-token' header
res.header('x-access-token', token);
...
});
use jwt.verify()
to verify the token.
final app = app();
final port = env('port') ?? 3000;
final jwt = jwt();
final secret = env('jwt_secret');
app.get('/', (req req, res res) {
// get token from 'x-access-token' header
final token = req.header('x-access-token');
try {
final data = jwt.verify(token, secret);
if (data != null) {
print(data['username']);
}
} on jwtexpirederror {
// handle jwtexpirederror
} on jwterror catch (e) {
// handle jwterror
} on exception catch (e) {
// handle exception
}
...
});
another way to verify the token.
final app = app();
final port = env('port') ?? 3000;
final jwt = jwt();
final secret = env('jwt_secret');
app.get('/', (req req, res res) {
// get token from client 'x-access-token' header
final token = req.header('x-access-token');
jwt.verify(token, secret, (error, data) {
if (data != null) {
print(data['username']);
}
if (error != null) {
print(error);
}
});
...
});
middleware
middleware is function that hooks into the routing process. it performs some operations before executing the route callback handler.
middleware is usually to edit the request or response object, or terminate the request before it reach the route callback.
you can add middleware like this.
app.use((req req, res res) async {
// do something
});
this is a bit similar as defining the route callback.
most of the time, you’ll be enough by using built in middlewares provided by lucifer, like the static
, cors
, session
that we’ve used before.
but if you need it, you can easily create your own middleware, and use it for a specific route by putting it in the middle between route and callback handler.
final app = app();
// create custom middleware
final custom = (req req, res res) async {
// do something here
};
// use the middleware for get / request
app.get('/', custom, (req req, res res) async {
await res.send('angels');
});
you can apply multiple middlewares to any route you want.
final app = app();
final verifytoken = (req req, res res) async {
// do something here
};
final authorize = (req req, res res) async {
// do something here
};
app.get('/user', [ verifytoken, authorize ], (req, res) async {
await res.send('angels');
});
if you want to save data in a middleware and access it from the next middlewares or from the route callback, use res.local()
final app = app();
final verifytoken = (req req, res res) async {
// saving token into the local data
res.local('token', 'jwt-token');
};
final authorize = (req req, res res) async {
// get token from local data
var token = res.local('token');
};
app.get('/user', [ verifytoken, authorize ], (req, res) async {
// get token from local data
var token = res.local('token');
});
there is no next()
to call in these middleware (unlike other framework like express).
processing next is handled automatically by lucifer.
a lucifer app will always run to the next middleware or callback in the current processing stack…
unless, you send some response to the client in the middleware, which will close the connection and automatically stop all executions of the next middlewares/callback.
since these call is automatic, you need to remember to use a proper async
await
when calling asynchronous functions.
as example, when using res.download()
to send file to the client.
app.get('/download', (req req, res res) async {
await res.download('somefile.pdf');
});
one simple rule to follow: if you call a function that returns future
or futureor
, play safe and use async
await
.
if in the middle of testing your application, you see an error in the console with some message like http headers not mutable
or headers already sent
, it’s an indicator that some parts of your application need to use proper async await
forms
now lets learn to process forms with lucifer.
say we have an html form:
<form method="post" action="/login">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" value="login" />
</form>
when user press the submit button, browser will automatically make a post request to /login
in the same origin of the page, and with it sending some data to the server, encoded as application/x-www-form-urlencoded
.
in this case, the data contains username
and password
form also can send data with get, but mostly it will use the standard & safe post method.
these data will be attached in the request body. to extract it, you can use the built in urlencoded
middleware.
final app = app();
app.use(urlencoded());
// always use xssclean to clean the inputs
app.use(xssclean());
we can test create a post endpoint for /login
, and the submitted data will be available from req.body
app.post('/login', (req req, res res) async {
final username = req.body['username']; // same as req.data('username');
final password = req.body['password']; // same as req.data('password');
...
await res.end();
});
file uploads
learn to handle uploading file(s) via forms.
lets say you have an html form that allows user to upload file.
<form method="post" action="/upload">
<input type="file" name="document" />
<input type="submit" value="upload" />
</form>
when user press the submit button, browser will automatically send a post request to /upload
in the same origin, and sending file from the input file.
it’s not sent as application/x-www-form-urlencoded
like the usual standard form, but multipart/form-data
handling multipart data manually can be tricky and error prone, so we will use a built in formparser
utility that you can access with app.form()
final app = app();
final form = app.form();
app.post('/upload', (req req, res res) async {
await form.parse(req, (error, fields, files) {
if (error) {
print('$error');
}
print(fields);
print(files);
});
});
you can use it per event that will be notified when each file is processed. this also notify other events, like on processing end, on receiving other non-file field, or when an error happened.
final app = app();
final form = app.form();
app.post('/upload', (req req, res res) async {
await form
.onfield((name, field) {
print('${name} ${field}');
})
.onfile((name, file) {
print('${name} ${file.filename}');
})
.onerror((error) {
print('$error');
})
.onend(() {
res.end();
})
.parse(req);
});
or use it like this.
final app = app();
final form = app.form();
app.post('/upload', (req req, res res) async {
await form
.on('field', (name, field) {
print('${name} ${field}');
})
.on('file', (name, file) {
print('${name} ${file}');
})
.on('error', (error) {
print('$error');
})
.on('end', () {
res.end();
})
.parse(req);
});
either way, you get one or more uploadedfile
objects, which will give you information about the uploaded files. these are some value you can use.
file.name
: to get the name from input filefile.filename
: to get the filenamefile.type
: to get the mime type of the filefile.data
: to get raw byte data of the uploaded file
by default, formparser
only include the raw bytes data and not save it into any temporary folder. you can easily handle this yourself like this.
import 'package:path/path.dart' as path;
// file is an uploadedfile object you get before
// save to uploads directory
string uploads = path.absolute('uploads');
// use the same filename as sent by the client,
// but feel free to use other file naming strategy
file f = file('$uploads/${file.filename}');
// check if the file exists at uploads directory
bool exists = await f.exists();
// create file if not exists
if (!exists) {
await f.create(recursive: true);
}
// write bytes data into the file
await f.writeasbytes(file.data);
print('file is saved at ${f.path}');
templating
lucifer provides default templating with mustache
engine. it uses a package mustache_template
that’s implemented from the official mustache spec.
by default, to keep the core framework light-weight, lucifer doesn’t attach any template engine to your app. to use the mustache
middleware, you need to apply it first.
final app = app();
app.use(mustache());
then these mustache
can render any template you have in the project views
directory.
say you have this index.html
in the views
directory.
<!doctype html>
<html>
<head></head>
<body>
<h2>{{ title }}</h2>
</body>
</html>
and render the template with res.render()
final app = app();
app.use(mustache());
app.get('/', (req req, res res) async {
await res.render('index', { 'title': 'hello detective' });
});
if you run command lucy run
and open http://localhost:3000 in the browser, it’ll shows an html page displaying hello detective
you can change the default views
with other directory you want.
final app = app();
// now use 'template' as the views directory
app.use(mustache('template'));
app.get('/', (req req, res res) async {
// can also use res.view()
await res.view('index', { 'title': 'hello detective' });
});
now if you add this index.html
file to the template
directory.
<!doctype html>
<html>
<head></head>
<body>
<h2>{{ title }} from template</h2>
</body>
</html>
then run the app and open it in the browser, it will shows another html page containing hello detective from template
for more complete details to use mustache
template engine, you can read the mustache manual.
to use other engines, such as jinja or jaded, you can manage the template rendering yourself, and then send the html by calling res.send()
app.get('/', (req req, res res) async {
// render your jinja/jaded template into 'html' variable
// then send it to the client
await res.send(html);
});
or you can create a custom middleware to handle templating with your chosen engine.
here is example you can learn from the mustache
middleware to create your own custom templating.
//
// name it with anything you want
//
callback customtemplating([string? views]) {
return (req req, res res) {
//
// you need to overwrite res.renderer
// using the chosen template engine
//
res.renderer = (string view, map<string, dynamic> data) async {
//
// most of the time, these 2 lines will stay
//
string directory = views ?? 'views';
file file = file('$directory/$view.html');
//
// file checking also stay
//
if (await file.exists()) {
//
// mostly, all you need to do is edit these two lines
//
template template = template(await file.readasstring());
string html = template.renderstring(data);
//
// in the end, always send the rendered html
//
await res.send(html);
}
};
};
}
to apply the new templating middleware, use app.use()
like before.
final app = app();
app.use(customtemplating());
security
lucifer has a built in security
middleware that covers dozens of standard security protections to guard your application. to use them, simply add it to your app with app.use()
final app = app();
app.use(security());
read here to learn more about web security.
error handling
lucifer automatically handle the errors that occured in your application. however, you can set your own error handling with app.on()
final app = app();
app.on(404, (req, res) {
// handle 404 not found error in here
// such as, showing a custom 404 page
});
// another way is using statuscode
app.on(statuscode.not_found, (req, res) { });
app.on(statuscode.internal_server_error, (req, res) { });
app.on(statuscode.bad_request, (req, res) { });
app.on(statuscode.unauthorized, (req, res) { });
app.on(statuscode.payment_required, (req, res) { });
app.on(statuscode.forbidden, (req, res) { });
app.on(statuscode.method_not_allowed, (req, res) { });
app.on(statuscode.request_timeout, (req, res) { });
app.on(statuscode.conflict, (req, res) { });
app.on(statuscode.unprocessable_entity, (req, res) { });
app.on(statuscode.not_implemented, (req, res) { });
app.on(statuscode.service_unavailable, (req, res) { });
you can trigger http exceptions from middleware or callback function.
app.get('/unauthorized', (req req, res res) async {
throw unauthorizedexception();
});
here is the list of all default exceptions we can use.
badrequestexception
unauthorizedexception
paymentrequiredexception
forbiddenexception
notfoundexception
methodnotallowedexception
requesttimeoutexception
conflictexception
unprocessableexception
internalerrorexception
notimplementedexception
serviceunavailableexception
parallel processing
parallel and multithread-ing is supported by default with dart/lucifer. it can be done by distributing the processes evenly in various isolates.
here is one way to do it.
import 'dart:async';
import 'dart:isolate';
import 'package:lucifer/lucifer.dart';
void main() async {
// start an app
await startapp();
// spawn 10 new app with each own isolate
for (int i = 0; i < 10; i++) {
isolate.spawn(spawnapp, null);
}
}
void spawnapp(data) async {
await startapp();
}
future<app> startapp() async {
final app = app();
final port = env('port') ?? 3000;
app.get('/', (req req, res res) async {
await res.send('hello detective');
});
await app.listen(port);
print('server running at http://${app.host}:${app.port}');
return app;
}
web socket
web socket is a necessary part of web application if you need persistent communications between client and server. here is an example to use web socket with lucifer.
import 'dart:io';
import 'package:lucifer/lucifer.dart';
void main() async {
final app = app();
final port = env('port') ?? 3000;
app.use(static('public'));
app.get('/', (req req, res res) async {
await res.sendfile('chat.html');
});
app.get('/ws', (req req, res res) async {
list clients = [];
final socket = app.socket(req, res);
socket.on('open', (websocket client) {
clients.add(client);
for (var c in clients) {
if (c != client) {
c.send('new human has joined the chat');
}
}
});
socket.on('close', (websocket client) {
clients.remove(client);
for (var c in clients) {
c.send('a human just left the chat');
}
});
socket.on('message', (websocket client, message) {
for (var c in clients) {
if (c != client) {
c.send(message);
}
}
});
socket.on('error', (websocket client, error) {
res.log('$error');
});
await socket.listen();
});
await app.listen(port);
print('server running at http://${app.host}:${app.port}');
}
contributions
feel free to contribute to the project in any ways. this includes code reviews, pull requests, documentations, tutorials, or reporting bugs that you found in lucifer.
license
mit license
copyright (c) 2021 lucifer
permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “software”), to deal in the software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the software, and to permit persons to whom the software is furnished to do so, subject to the following conditions:
the above copyright notice and this permission notice shall be included in all copies or substantial portions of the software.
the software is provided “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. in no event shall the
authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the
software.
Comments are closed.