domingo, 24 de marzo de 2013

Dart on Heroku. A 30 seconds guide.

Did you know that you can run your server-side Dart app on Heroku's cloud? Yes, and this is really simple. Heroku cloud is a great resource for quick deployment. Moreover there is free for simple deployments!.
Let's start by signing up on Heroku site, a very simple procedure:





After loading the Git Bash application we have all we need. First we need to write the server, in some directory we will write the file main.dart, here is the complete code:


import 'dart:io';
import 'dart:json' as JSON;

main() {
 var port = int.parse(Platform.environment['PORT']);

  HttpServer.bind('0.0.0.0', port).then((HttpServer server) {
    print('Server started on port: ${port}');
    server.listen((HttpRequest request) {
      var resp = JSON.stringify({
        'Dart on Heroku': true,
        'Buildpack URL': 'https://github.com/igrigorik/heroku-buildpack-dart',
        'Environment': Platform.environment}
      );
      request.response..headers.set(HttpHeaders.CONTENT_TYPE, 'application/json')
                      ..write(resp)
                      ..close();
    });
  });
}


The code is simple. Any request to the Heroku server will return a response (JSON formatted) with information about environment variables.
We need to write another file in the same directory. The file will be named Procfile and the content is:

web: ./dart-sdk/bin/dart main.dart


That's all. Now we just have to push the two files to the Heroku cloud. Remember Heroku uses a  git based deploy.

$> cd
$> git init
$> git add .
$> git commit -am "first commit"

Next  create an Heroku app. (Change myapp_name for the name of your app)

$> heroku create myapp_name
$> heroku config:add BUILDPACK_URL=https://github.com/igrigorik/heroku-buildpack-dart.git

Finally, push the app up to the Heroku cloud.

$> git push heroku master


You should see something like:


-----> Heroku receiving push
-----> Fetching custom buildpack... done
-----> Dart app detected
-----> Installing latest Dart VM
-----> Discovering process types
       Procfile declares types -> web
-----> Compiled slug size is 10.6MB
-----> Launching... done, v5
       http://myapp_name.herokuapp.com deployed to Heroku


That's all! You now have a Dart server app running in the cloud.
Open your browser and point to: http://myapp_name.herokuapp.com you will be answered with the JSON file:


{"Dart on Heroku":true,"Buildpack URL":"https://github.com/igrigorik/heroku-buildpack-dart","Environment":{"HOME":"/app","BUILDPACK_URL":"https://github.com/igrigorik/heroku-buildpack-dart.git","SHLVL":"1","PS1":"\\[\\033[01;34m\\]\\w\\[\\033[00m\\] \\[\\033[01;32m\\]$ \\[\\033[00m\\]","_":"./dart-sdk/bin/dart","PATH":"/app/bin:/usr/local/bin:/usr/bin:/bin","PWD":"/app","PS":"web.1","PORT":"6640"}}

No hay comentarios: