Validating HTTP methods
Most modern web applications have a way of restricting requests to a route based on the HTTP method. In this section, we will see how to restrict our handlers to work with a specific HTTP method in a Cowboy-based web application. The simplest way of accomplishing that in a Cowboy handler is by pattern matching on the first argument of the init/2
function, which is the request. A Cowboy request contains a lot of information, including the HTTP method used to make the request. So, by pattern matching on the request with a specific HTTP method, we can filter requests based on HTTP methods. However, we will also be needing a general clause for the init/2
function, which responds with a 404 error
.
In the Greet
handler, let us update init/2
to match only on requests with the GET
method, along with another clause that responds with a 404 (Not
Found)
error:
lib/cowboy_example/router/handlers/greet.ex
defmodule CowboyExample.Router.Handlers.Greet do # .. def init(%{method: "GET"} = req0, state) do # .. end # General clause for init/2 which responds with 404 def init(req0, state) do Logger.info("Received request: #{inspect req0}") req1 = :cowboy_req.reply( 404, %{"content-type" => "text/html"}, "404 Not found", req0 ) {:ok, req1, state} end end
Now, let’s make sure only GET
requests are accepted by our server for the route. Let’s first make sure GET
requests are working:
$ curl http://localhost:4040/greet/Elixir\?greeting=Hola Hola Elixir%
It’s time to check that a POST
request for the greet
route returns a 404
error:
$ curl http://localhost:4040/greet/Elixir\?greeting=Hola -X POST 404 Not found%
This ensures that our route works only for GET
requests. Another way of validating HTTP methods of our requests would be by using Cowboy middleware, but we will not be covering that in this chapter.
Cowboy middleware
In Cowboy, middleware is a way to process an incoming request. Every request has to go through two types of middleware (the router and the handler), but Cowboy allows us to define our own custom middleware module, which gets executed in the given order. A custom middleware module just needs to implement the execute/2
callback defined in the cowboy_middleware
behavior.
Great! We have successfully enforced a method type for a route. Next, we will learn how to serve HTML files instead of raw strings.