Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Build Your Own Web Framework in Elixir

You're reading from   Build Your Own Web Framework in Elixir Develop lightning-fast web applications using Phoenix and metaprogramming

Arrow left icon
Product type Paperback
Published in Jun 2023
Publisher Packt
ISBN-13 9781801812542
Length 274 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Aditya Iyengar Aditya Iyengar
Author Profile Icon Aditya Iyengar
Aditya Iyengar
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Part 1: Web Server Fundamentals
2. Chapter 1: Introducing the Cowboy Web Server FREE CHAPTER 3. Chapter 2: Building an HTTP Server in Elixir 4. Part 2: Router, Controller, and View
5. Chapter 3: Defining Web Application Specifications Using Plug 6. Chapter 4: Working with Controllers 7. Chapter 5: Adding Controller Plugs and Action Fallback 8. Chapter 6: Working with HTML and Embedded Elixir 9. Chapter 7: Working with Views 10. Part 3: DSL Design
11. Chapter 8: Metaprogramming – Code That Writes Code 12. Chapter 9: Controller and View DSL 13. Chapter 10: Building the Router DSL 14. Index

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.

You have been reading a chapter from
Build Your Own Web Framework in Elixir
Published in: Jun 2023
Publisher: Packt
ISBN-13: 9781801812542
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime