Skip to content

Instantly share code, notes, and snippets.

@o0101
Forked from flbuddymooreiv/readme.md
Created August 16, 2018 13:54
Show Gist options
  • Save o0101/cc33424af08d5bedf8a4cf6c305bc80d to your computer and use it in GitHub Desktop.
Save o0101/cc33424af08d5bedf8a4cf6c305bc80d to your computer and use it in GitHub Desktop.
erlang + rebar + cowboy Hello World

This is the process of setting up erlang, rebar3, and cowboy for a Hello World, starting with a clean Debian 8 install.

Update apt and install deps:

root@046edcaea45a:~# apt-get update
root@046edcaea45a:~# apt-get install erlang erlang-dev gcc
root@046edcaea45a:~# wget https://s3.amazonaws.com/rebar3/rebar3
root@046edcaea45a:~# mkdir ~/bin/
root@046edcaea45a:~# mv rebar3 ~/bin/
root@046edcaea45a:~# chmod +x ~/bin/rebar3 

Create the rebar project:

root@046edcaea45a:~# ~/bin/rebar3 new release cowboy_hello_world 
root@046edcaea45a:~# cd cowboy_hello_world/

Put the following entry in the rebar.config deps tuple and add the rebar3_run plugin:

root@046edcaea45a:~/cowboy_hello_world# vi rebar.config 
{deps, [
        {cowboy, {git, "https://github.com/ninenines/cowboy", {tag, "2.0.0-pre.1"}}}
]}.

{plugins, [rebar3_run]}.

Add cowboy to the list {application, [{applications, [kernel, stdlib, cowboy]}]}

root@046edcaea45a:~/cowboy_hello_world# vi apps/cowboy_hello_world/src/cowboy_hello_world.app.src 

Register a handler for the / url

root@046edcaea45a:~/cowboy_hello_world# vi apps/cowboy_hello_world/src/cowboy_hello_world_app.erl  
start(_StartType, _StartArgs) ->
    {ok, Pid} = 'cowboy_hello_world_sup':start_link(),
    Routes = [ {
        '_',
        [
            {"/", cowboy_hello_world_root, []}
        ]
    } ],
    Dispatch = cowboy_router:compile(Routes),

    NumAcceptors = 10,
    TransOpts = [ {ip, {0,0,0,0}}, {port, 2938} ],
    ProtoOpts = [{env, [{dispatch, Dispatch}]}],

    {ok, _} = cowboy:start_http(chicken_poo_poo,
        NumAcceptors, TransOpts, ProtoOpts),

    {ok, Pid}.

Create the handler referenced above:

root@046edcaea45a:~/cowboy_hello_world# vi apps/cowboy_hello_world/src/cowboy_hello_world_root.erl
-module(cowboy_hello_world_root).

-export([init/2]).

init(Req, Opts) ->
    Req2 = cowboy_req:reply(200,
        [{<<"content-type">>, <<"text/plain">>}],
        <<"Hello Erlang!">>,
        Req),
    {ok, Req2, Opts}.
root@046edcaea45a:~/cowboy_hello_world# ~/bin/rebar3 run

Browse to http://localhost:2938 and win.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment