httpelixircowboy

Elixir - How do I manage routes using Cowboy (and nothing else)?


I'm restricted to only using Cowboy for a web server that handles a JSON REST API. I need to be able to use only Cowboy + whatever the language capabilities are to manage and process different and variable routes, as well as using the GET values.

I'm getting the path as explained in the following routine:

def handle(req, router) do
  headers = [{"content-type", "application/json"}]
  {path, req}  = :cowboy_req.path(req)
  {:ok, resp} = :cowboy_req.reply(200, headers, router.call(path), req)
  {:ok, resp, router}
end

And ultimately route.call(path) calls the following:

defp serve("/call/[:thing]") do
  list = [path: "oy"]
  IO.puts :thing
  {status, result} = JSON.encode(list)
  result
end

By itself, serve("/call") returns the JSON without issues, but trying to request any other route under /call to the server, makes it answer with the 404 response (already handled by me).

What's the best approach when handling these dynamic routes? Bear in mind that I'm delimited to only using Cowboy and nothing else.


Solution

  • Your code is not very clear - how did you start the server? More specifically, how did you setup your router? This seems to be the problem here, I'm guessing you made a route only for /call.

    You'd need something like this:

    dispatch_config = :cowboy_router.compile([{:_, [{"/call/[:thing]", YourHandlerModule, []}]}])
    { :ok, _ } = :cowboy.start_http(:http,
                                    100,
                                    [{:port, 8080}],
                                    [{ :env, [{:dispatch, dispatch_config}]}]
                                    )
    

    The path /call/[:thing] should be specified at the router, not inside your handler.