Skip to content

Instantly share code, notes, and snippets.

@archaelus
Created June 1, 2012 23:50
Show Gist options
  • Save archaelus/2855839 to your computer and use it in GitHub Desktop.
Save archaelus/2855839 to your computer and use it in GitHub Desktop.
Cowboy rest
%% @copyright Geoff Cant
%% @author Geoff Cant <[email protected]>
%% @version {@vsn}, {@date} {@time}
%% @doc Default HTTP handler for Logmachine.
%% @end
-module(lm_logs_rest).
-export([init/3
,rest_init/2
,known_methods/2
,allowed_methods/2
,content_types_accepted/2
,from_logplex/2
,content_types_provided/2
,to_response/2
]).
init(_Transport, _Req, _Opts) ->
{upgrade, protocol, cowboy_http_rest}.
rest_init(Req, _Opts) ->
{ok, Req, undefined}.
allowed_methods(Req, State) ->
{['PUT'], Req, State}.
known_methods(Req, State) ->
{['PUT'], Req, State}.
content_types_accepted(Req, State) ->
{[{{<<"application">>, <<"x-logplex">>, []}, from_logplex}],
Req, State}.
from_logplex(Req, State) ->
case cowboy_http_req:body(Req) of
{ok, Body, Req1} ->
io:format(standard_io, "Got a valid logplex body.~n", []),
{true, Req1, Body};
{error, Why} ->
io:format(standard_io, "Invalid logplex body: ~p.~n", [Why]),
{false, Req, State}
end.
content_types_provided(Req, State) ->
{[{{<<"text">>, <<"plain">>, []}, to_response}],
Req, State}.
to_response(Req, undefined) ->
{"UNDEFINED", Req};
to_response(Req, _Body) ->
{"DEFINED", Req}.
@archaelus
Copy link
Author

curl -X PUT -H "Content-Type: application/x-logplex" -T ~/heroku/tmp/snippet.logplex -v http://localhost:5000/logs
* About to connect() to localhost port 5000 (#0)
*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 5000 (#0)
> PUT /logs HTTP/1.1
> User-Agent: curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5
> Host: localhost:5000
> Accept: */*
> Content-Type: application/x-logplex
> Content-Length: 60
> Expect: 100-continue
> 
< HTTP/1.1 406 Not Acceptable
< Content-Length: 0
< Date: Fri, 01 Jun 2012 23:46:07 GMT
< Server: Cowboy
< Connection: keep-alive
< 
* Connection #0 to host localhost left intact
* Closing connection #0

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