Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cowboy HTTP POST handlers

Tags:

erlang

cowboy

I'm started learing Erlang. I want to write simple cowboy-based HTTP server, which can receive files sending via HTTP POST. So I create simple handler:

-module(handler).
-behaviour(cowboy_http_handler).
-export([init/3,handle/2,terminate/3]).

init({tcp, http}, Req, _Opts) ->
  {ok, Req, undefined_state}.

handle(Req, State) ->
  Body = <<"<h1>Test</h1>">>,
  {ok, Req2} = cowboy_req:reply(200, [], Body, Req),
  {ok, Req2, State}.

terminate(_Reason, _Req, _State) ->
  ok.

This code can handle GET request. But how can I process HTTP POST request?

like image 379
John Ostin Avatar asked Oct 22 '25 07:10

John Ostin


1 Answers

Your code handles requests with any HTTP methods. If you want to handle particular HTTP request method you have to test the method name in callback handle/2. Here you can see a simple example:

handle(Req, State) ->
    {Method, Req2} = cowboy_req:method(Req),
    case Method of
        <<"POST">> ->
            Body = <<"<h1>This is a response for POST</h1>">>;
        <<"GET">> ->
            Body = <<"<h1>This is a response for GET</h1>">>;
        _ ->
            Body = <<"<h1>This is a response for other methods</h1>">>
    end,
    {ok, Req3} = cowboy_req:reply(200, [], Body, Req2),
    {ok, Req3, State}.

To get a content of POST request you can use function cowboy_req:body_qs/2 for example. There are other functions for handling body of HTTP requests in cowboy. Check the documentation and choose the way which is convenient for you.

like image 172
Danil Onishchenko Avatar answered Oct 25 '25 06:10

Danil Onishchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!