About this ebook
- Use Clojure to create robust, ready-to-be deployed web applications
- Get to grips with Clojure through successive implementation of applications using new features
- Explore the in-depth concepts of Clojure, such as templating, request routing, input validation, and database transactions, and utilize Java interoperability
This book is for anyone who's worked with Clojure and wants to use it to start developing applications for the Web. Experience or familiarity with basic Clojure syntax is a must, and exposure to Leiningen (or other similar build tools such as Maven) would be helpful.
Ryan Baldwin
Ryan “Liberation” Baldwin was born on May 10, 1979 in Evanston, Illinois. He spent his youthful years there, on Chicago’s Northside, and in College Park, GA, before returning to the Northside of Chicago, and getting himself in a situation that transformed his life forever. While living in separation from society, Mr. Baldwin had to swiftly learn discipline and to stand ten-toes down, to fend for self within the jungles of the Illinois Department of Corrections from the tender ages of 17-to-27 years of age. With plenty of time on his hands, he learned from his mistakes, as well as, from the shining examples demonstrated before him,by family members and loved ones. He embraced GOD & began establishing a relationship with HIM that’s still alive. He also discovered his passion for writing poetry with positive messages customized to inspire, uplift & encourage others to embrace GOD and experience the light which THE MOST HIGH had placed before HIS path. Mr. Baldwin humbly gives GOD all the glory, praise & honor for the good in his life, looks beyond the difficult, expects the best, even through the worse of times & sees the condition of the Black community in America as being one of his major inspirations for writing. He has found self-expression as a marvelous way to release stress & unneeded energy. He also attended Lake Land Community College while incarcerated and earned his Associate’s Degree, undertook Business Management, Public Speaking, English, Strategies for Life, etc…. Mr. Baldwin, is also a Motivational Speaker/Mentor. He volunteers with Destiny’s Changer International, LLC. He has a record of volunteering in youth programs and envisions himself establishing an enrichment program for “at-risk” youth growing up in urban communities within America.
Related to Clojure Web Development Essentials
Related ebooks
Learning Rust Rating: 0 out of 5 stars0 ratingsModern Web Development with Go: Build real-world, fast, efficient and scalable web server apps using Go programming language Rating: 0 out of 5 stars0 ratingsJump Start PHP Environment: Master the World's Most Popular Language Rating: 0 out of 5 stars0 ratingsProgramming Backend with Go Rating: 0 out of 5 stars0 ratingsBackend Handbook: for Ruby on Rails Apps Rating: 1 out of 5 stars1/5Python for Google App Engine Rating: 0 out of 5 stars0 ratingsClojure Data Analysis Cookbook - Second Edition Rating: 5 out of 5 stars5/5Clojure for Java Developers Rating: 0 out of 5 stars0 ratingsLearn ClojureScript: Functional programming for the web Rating: 0 out of 5 stars0 ratingsClojure Programming Cookbook Rating: 0 out of 5 stars0 ratingsThe Clojure Workshop: Use functional programming to build data-centric applications with Clojure and ClojureScript Rating: 0 out of 5 stars0 ratingsClojure High Performance Programming, Second Edition: Become an expert at writing fast and high performant code in Clojure 1.7.0 Rating: 0 out of 5 stars0 ratingsElixir Programming Fundamentals: A Concise Guidebook Rating: 0 out of 5 stars0 ratingsMastering Scala: Elegance in Code Rating: 0 out of 5 stars0 ratingsCode Beneath the Surface: Mastering Assembly Programming Rating: 0 out of 5 stars0 ratingsClojure Reactive Programming Rating: 0 out of 5 stars0 ratingsScientific Computing with Scala Rating: 0 out of 5 stars0 ratingsLearning Elixir: Unveil many hidden gems of programming functionally by taking the foundational steps with Elixir Rating: 0 out of 5 stars0 ratingsClojure Data Structures and Algorithms Cookbook Rating: 4 out of 5 stars4/5Mastering Clojure: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsLearning ClojureScript Rating: 0 out of 5 stars0 ratingsHaskell from Another Site Rating: 0 out of 5 stars0 ratingsRust Mini Reference: A Hitchhiker's Guide to the Modern Programming Languages, #5 Rating: 0 out of 5 stars0 ratingsLLVM Cookbook Rating: 1 out of 5 stars1/5Elixir Cookbook Rating: 0 out of 5 stars0 ratingsElixir Programming: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsLearning RabbitMQ with C#: A magical tool for the IT world Rating: 0 out of 5 stars0 ratingsPractical Rust 1.x Cookbook Rating: 0 out of 5 stars0 ratings
System Administration For You
CompTIA A+ Complete Review Guide: Core 1 Exam 220-1101 and Core 2 Exam 220-1102 Rating: 5 out of 5 stars5/5Linux Bible Rating: 0 out of 5 stars0 ratingsCybersecurity: The Beginner's Guide: A comprehensive guide to getting started in cybersecurity Rating: 5 out of 5 stars5/5Learning Microsoft Endpoint Manager: Unified Endpoint Management with Intune and the Enterprise Mobility + Security Suite Rating: 0 out of 5 stars0 ratingsLinux Commands By Example Rating: 5 out of 5 stars5/5Bash Command Line Pro Tips Rating: 5 out of 5 stars5/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5CompTIA A+ Complete Practice Tests: Core 1 Exam 220-1101 and Core 2 Exam 220-1102 Rating: 0 out of 5 stars0 ratingsMastering Windows 365: Deploy and Manage Cloud PCs and Windows 365 Link devices, Copilot with Intune, and Intune Suite Rating: 0 out of 5 stars0 ratingsLearn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5Git Essentials Rating: 4 out of 5 stars4/5PowerShell: A Beginner's Guide to Windows PowerShell Rating: 4 out of 5 stars4/5Operating Systems DeMYSTiFieD Rating: 0 out of 5 stars0 ratingsWordpress 2023 A Beginners Guide : Design Your Own Website With WordPress 2023 Rating: 0 out of 5 stars0 ratingsLinux Kernel Programming: A comprehensive and practical guide to kernel internals, writing modules, and kernel synchronization Rating: 0 out of 5 stars0 ratingsMastering Linux Network Administration Rating: 4 out of 5 stars4/5Practical Data Analysis Rating: 4 out of 5 stars4/5Getting Started with Docker: Master the Art of Containerization with Docker Rating: 0 out of 5 stars0 ratingsThe Linux Command Line, 2nd Edition: A Complete Introduction Rating: 4 out of 5 stars4/5Intro to Bluetooth Low Energy: Learn Bluetooth Low Energy in a single weekend Rating: 0 out of 5 stars0 ratingsNetworking for System Administrators: IT Mastery, #5 Rating: 5 out of 5 stars5/5Infrastructure as Code (IAC) Cookbook Rating: 0 out of 5 stars0 ratingsDigital Legacy Plan: A guide to the personal and practical elements of your digital life before you die Rating: 0 out of 5 stars0 ratings
Reviews for Clojure Web Development Essentials
0 ratings0 reviews
Book preview
Clojure Web Development Essentials - Ryan Baldwin
Table of Contents
Clojure Web Development Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Getting Started with Luminus
Leiningen
Using Leiningen
Generating the application
Getting help
Dependencies of the app
Luminus file structure
util.clj
session_manager.clj
layout.clj
middleware.clj
routes/home.clj
handler.clj
repl.clj
Summary
2. Ring and the Ring Server
Understanding Ring in Clojure
Request maps
Response maps
Handlers
Middleware
Adapters
What is the Ring Server?
hipstr.handler
Initialization hooks
Shutdown hooks
App routes
The application handler
hipstr.repl
Start-server
Stop-server
Get-handler
Configuring and running the Ring Server
Summary
3. Logging
What is Timbre?
What is an appender?
Configuring a Timbre appender
Timbre log levels
Appender configuration keys
Appender map
Shared appender configuration
Logging with Timbre
Adding an appender
Adding the rolling appender
Summary
4. URL Routing and Template Rendering
What is Compojure?
Creating a Compojure route
Using defroutes
Anatomy of a route
Defining the method
Defining the URL
Parameter destructuring
Destructuring the request
Destructuring unbound parameters
Constructing the response
Generating complex responses
What is Selmer?
Creating your first page
Rendering a page
Variables
Filters
Filter parameters
Tags
Template inheritance
Editing the home page
Serving the signup form
Creating the signup page
Summary
5. Handling Form Input
Handling the form POST
Validating the form POST
The noir.validation namespace
The Validateur library
Adding the Validateur dependency
Creating the user validation namespace
Validating required fields
Validating the format
Validating length of values
Validation predicates
Making reusable validators
Reporting errors to the user
Summary
6. Testing in Clojure
The necessity of testing
Anatomy of a test
Writing and running our first test
Running tests
Running tests automatically
Refactoring tests
Writing a high-level integration test
Using ring.mock.request
Summary
7. Getting Started with the Database
Creating the database schema
Maintaining the database schema
Migratus
Getting Migratus
Configuring Migratus
Creating the user table
Dropping the user table
Running the down scripts
Migrating the database
Running all migration scripts from Leiningen
Running migrations programatically
Adding migrations to the hipstr initialization
Adding data to the database
What is YeSQL?
Getting YeSQL
Adding a user to the database
Inserting a user using SQL
Inserting a user using Clojure
Bringing it all together
Adjusting the route
Encrypting the password
Summary
8. Reading Data from the Database
Creating the catalog
Creating the artists table
Seeding the artists table
Creating the albums table
Fetching albums from the database
Writing the SQL query
Creating the albums model
Refactoring the connection
Creating the recently added route
Rendering the results
An exercise!
Summary
9. Database Transactions
Introduction to Database Transactions
The ACID properties
Importance of database transactions
Implementing a transaction
Transactions in Clojure
Transactions in YeSQL
Extending the application requirements in brief
Creating the add artist/album form
Creating the form
Abstracting the form
Creating the add artist/album endpoint
Creating the Compojure route
Creating the route helper function
Validating the add artist/album form
Expanding the album model
Wrapping the whole thing in a transaction
Using a transaction outside of this scope
Summary
10. Sessions and Cookies
Sessions
Setting up sessions
Interacting with the session
Restricted routes
Restricting route access
Accessing a restricted route
Access rule as a function
Access rule as a map
Cookies
Getting a cookie's value
Setting a cookie's value
Setting the cookie as a map
Securing a cookie
Deleting a cookie
Extending the application: brief requirements
Creating the login form
Restricting the recently-added route
Restricting the route
Checking if the user is authenticated
Defining the access rule
Authenticating the user
Validating the credentials
Handling the form POST
Writing the Remember Me
cookie
Creating the logout route
Summary
11. Environment Configuration and Deployment
Environ
Using environ
Variable translations
Setting and resolving environment configurations
Resolving environment configuration
Adjusting the database connection
Creating the profiles.clj file
Modifying the hipstr.models.connection namespace
Deploying the hipstr application
When to use an uberjar
When to use an uberwar
Deploying as a standalone
Running the application behind Nginx
Load balancing behind Nginx
Summary
A. Using Korma – a Clojure DSL for SQL
Getting Korma
The Quick Korma Crash Course
Define the database specification
Korma entities
Defining the primary key
Defining relationships between entities
Constructing SELECT queries
Constructing INSERT queries
Constructing UPDATE queries
Constructing DELETE queries
Using raw SQL
Using transactions
Port the models from YeSQL to Korma
Porting hisptr.models.connection
Porting hisptr.models.user-model
Porting hipstr.models.album-model
Index
Clojure Web Development Essentials
Clojure Web Development Essentials
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: February 2015
Production reference: 1180215
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78439-222-2
www.packtpub.com
Credits
Author
Ryan Baldwin
Reviewers
Eduardo Díaz
Shu Wang
Nate West
Daniel Ziltener
Commissioning Editor
Usha Iyer
Acquisition Editor
Neha Nagwekar
Content Development Editor
Rohit Kumar Singh
Technical Editors
Prajakta Mhatre
Rohith Rajan
Copy Editors
Pranjali Chury
Veena Mukundan
Vikrant Phadke
Project Coordinator
Mary Alex
Proofreaders
Ting Baker
Maria Gould
Indexer
Mariammal Chettiyar
Graphics
Disha Haria
Abhinash Sahu
Production Coordinator
Manu Joseph
Cover Work
Manu Joseph
About the Author
Ryan Baldwin is a theatre major turned computer science geek. Hailing from the prairies of Western Canada, Ryan has been developing software on a wide array of platforms and technologies since 2001. Once, he wrote a crazy system application that compiled XSD Schema Docs into XAML forms that performed two-way binding with underlying XML documents in .NET WPF. Why? Because it had to be done. Another time, he worked on a project that mashed many social networks into one gigantic thing that essentially allowed users to find out all of their indirect connections. It was eventually shelved.
In 2012, he relocated to Toronto, where he works with the University Health Network, developing systems and tools that facilitate patient information exchange. You can often find him wearing headphones and jittering in coffee shops.
I'd like to thank Packt for giving me this opportunity and Dmitri Sotnikov for pushing me to do it. Without either of you, I probably would have gotten a lot more sleep and a lot less experience out of life. I'd also like to thank Chris Kay Fraser, without whose support and vegan brownies I would have never had the confidence to pursue such a project. I'd finally like to thank my family, friends, colleagues, and anybody else who interacted with me over these past several months; I'll buy you a thank you
beer for putting up with me. All my reviewers who took the time to read, recheck, and provide essential feedback, I owe all of you at least a pitcher of beer (hit me up next time you're in Toronto). And, of course, I'd like to thank you, dear readers; without you, none of this would have happened. I am both humbled and terrified of you.
About the Reviewers
Eduardo Díaz is a Java developer, with experience particularly in web development. He has been interested in finding new programming paradigms and languages since he started developing software.
Clojure (and functional programming with Clojure) caught Eduardo's attention as an excellent mixture of a very unique paradigm and a pragmatic approach to programming. He has used it to build a data collection platform for several high-traffic sites, similar to Google Analytics. Clojure was an excellent choice for him, because it minimized errors and development time.
Writing this book was an incredible idea! More developers need to know the power of Clojure and how it can make their lives better. Thank you Ryan Baldwin and everyone involved in making this book happen!
Nate West is a polyglot web developer based in Nashville, Tennessee. While he has yet to meet a language he doesn't like, he found his home in the land of Lisp. As a developer at Blue Box, he gets paid to write in Ruby. When not learning new languages, he enjoys hanging out with his wife, playing with his dog, philosophizing over a cup of coffee, and mentoring at Nashville Software School.
Daniel Ziltener was born in the canton of Bern in Switzerland. He started programming at the age of 10 and acquired broad general knowledge about programming and software engineering, including desktop and web development and the programming languages such as Java, C++, Scala, Clojure, and Scheme. He started his studies in computer science at the University of Bern in 2012. Since then, he has worked as a Clojure software developer at the university's historical institute.
I'd like to thank the awesome Clojure community for all the great libraries and their support, especially in #Clojure, while I was learning Clojure a few years ago—it's been since 1.3! I'd also like to thank my employer for regularly giving me time off to review this book. You all really enabled me to become a Clojure pro.
www.PacktPub.com
Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
Support files, eBooks, discount offers, and morehttps://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Preface
Clojure is a beautiful, concise language, and its adoption for web applications is ready and about to explode. In Clojure Web Development Essentials, you will learn how to build a Clojure web application from scratch using the Leiningen build tool and the Luminus application template. We'll start by creating a simple example application in the first few pages of the first chapter, and build on that application with each subsequent chapter. We'll cover URL routing, template rendering, database connectivity, form validation, and everything else we need to build a typical web app. By the end of this book, you'll have the knowledge required to venture into the world of web development, and you'll be able to use your skills for the betterment of the Internet.
What this book covers
Chapter 1, Getting Started with Luminus, guides you through creating a new project using the Luminus application template. We'll then dive into what was generated, what the out-of-the-box project dependencies are, and the general file structure of a Luminus web app.
Chapter 2, Ring and the Ring Server, describes the core technologies driving our application, and shows you how to use the development web server.
Chapter 3, Logging, demonstrates configuration of some basic logging and the Clojure logging library, Timbre.
Chapter 4, URL Routing and Template Rendering, starts to dive into the important part of web applications. It shows you how to handle incoming requests using Compojure, and how to render web pages using the Selmer templating engine. We'll also create a sign-up form for our application.
Chapter 5, Handling Form Input, teaches you how to validate form data and report form validation errors back to the user.
Chapter 6, Testing in Clojure, is a quick tour of automated testing and its use in Clojure.
Chapter 7, Getting Started with the Database, is the first of three chapters covering database management and interactivity. We'll set up our application's database, and you will learn how to manage your database schema using the Migratus Leiningen plug. Then we will store the form input created in the fifth chapter using YeSQL.
Chapter 8, Reading Data from the Database, continues exploring database interactivity by teaching you how to retrieve data from the database using YeSQL. We'll then create a couple of new web pages that list the most recently added items in our database.
Chapter 9, Database Transactions, gives us a brief overview of what database transactions are. We'll then create a form that transactionally inserts data into multiple tables.
Chapter 10, Sessions and Cookies, demonstrates how sessions and cookies are managed and maintained in Noir. We'll then create an authentication form for our application, and save a cookie in the user's browser to remember their username the next time they log in.
Chapter 11, Environment Configuration and Deployment, guides us through abstracting our environment configuration (such as database connectivity) and describes a few common ways by which we can deploy our application.
Appendix, Using Korma – a Clojure DSL for SQL, covers the modification of the YeSQL model layers to use Korma, a native Clojure Domain Specific Language that can be used to interact with the database if you're not keen on using raw SQL.
What you need for this book
First and foremost, you must be familiar with the Clojure programming language. You'll also need to install the Leiningen build tool. Familiarity with basic web technology is also valuable.
Who this book is for
This book targets software developers who are already using Clojure but want to use their skill set for web applications. Very little of this book does any fancy frontend development, and most of it focuses on server-side development. If you're primarily a frontend developer, or have never heard of Clojure, this book is precisely not what you are looking for.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles and explanations of their meanings.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: We can include other contexts through the use of the include directive.
A block of code is set as follows:
:dependencies [[org.clojure/clojure 1.6.0
]
[lib-noir 0.9.4
]
[ring-server 0.3.1
]
[selmer 0.7.2
]
[com.taoensso/timbre 3.3.1
]
[com.taoensso/tower 3.0.2
]
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
:ring {:handler hipstr.handler/app
:init hipstr.handler/init
:destroy hipstr.handler/destroy
:open-browser? false}
Any command-line input or output is written as follows:
# lein ring server-headless
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: clicking the Next button moves you to the next screen.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may