[erlang-questions] problems with cowboy hello world

Loïc Hoguin essen@REDACTED
Thu Mar 12 09:57:47 CET 2015

On 03/12/2015 06:07 AM, Kenneth Lakin wrote:
> If you're using Cowboy 1.0.x, (as I am), then I learned that you can't
> actually make a response in init/3. (I got exactly the same stacktrace
> that you're reporting.) All work has to be done in handle/2.

In 1.0.x you can reply in init/3, but you still have to have a handle/2 

> This *should* be a correct Cowboy 1.0.x Hello World:
> -module( hello_api ).
> -export([ init/3, handle/2, terminate/3 ]).
> handle(Req, State) ->
>    {ok, Req2} = cowboy_req:reply(200, [
>                                  {<<"content-type">>, <<"text/plain">>}
>                                 ], <<"Hello World!">>, Req),
>    {ok, Req2, State}.
> init(_Type, Req, _Opts) ->
>    {ok, Req, no_state}.
> terminate(_Reason, _Req, _State) ->
>    ok.
> I can't speak to how you would do this with with Cowboy HEAD.

Just remove init/3, remove terminate/3 (it's become optional), rename 
handle/2 into init/2 and fix the return value of cowboy_req:reply to "Req".

-module( hello_api ).
-export([ init/2 ]).

handle(Req, State) ->
     {ok, cowboy_req:reply(200,
         [{<<"content-type">>, <<"text/plain">>}],
         <<"Hello World!">>, Req), State}.

> (As an aside, I very much dislike how erlang.mk treats all warnings as
> errors. I'm much more pleased when using rebar as a build system.)

It's just the default, you can easily change it. I would advise fixing 
those warnings instead, though.

Loïc Hoguin

More information about the erlang-questions mailing list