Rust Web Development (Bastian Gruber) (z-library.sk, 1lib.sk, z-lib.sk)
Author: Bastian Gruber
RUST
Create bulletproof, high-performance web apps and servers with Rust. In Rust Web Development you will learn: Handling the borrow checker in an asynchronous environment Learning the ingredients of an asynchronous Rust stack Creating web APIs and using JSON in Rust Graceful error handling Testing, tracing, logging, and debugging Deploying Rust applications Efficient database access
📄 File Format:
PDF
💾 File Size:
3.9 MB
6
Views
0
Downloads
0.00
Total Donations
📄 Text Preview (First 20 pages)
ℹ️
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
📄 Page
1
(This page has no text content)
📄 Page
2
inside front cover
📄 Page
3
(This page has no text content)
📄 Page
4
Rust Web Development WITH WARP, TOKIO, AND REQWEST BASTIAN GRUBER To comment go to liveBook Manning Shelter Island For more information on this and other Manning titles go to
📄 Page
5
www.manning.com
📄 Page
6
Copyright For online information and ordering of these and other Manning books, please visit www.manning.com. The publisher offers discounts on these books when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2023 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. ♾ Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to
📄 Page
7
that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. 20 Baldwin Road Technical PO Box 761 Shelter Island, NY 11964 Development editor: Elesha Hyde Technical development editor: Tanya Wilke Review editor: Mihaela Batinić Production editor: Kathleen Rossland Copy editor: Sharon Wilkey Proofreader: Jason Everett Technical proofreaders: Troi Eisler and Jerry Kuch Typesetter: Dennis Dalinnik Cover designer: Marija Tudor ISBN: 9781617299001
📄 Page
8
dedication To Emily, Cora, and Marlo
📄 Page
9
contents front matter preface acknowledgments about this book about the author about the cover illustration Part 1 Introduction to Rust 1 Why Rust? 1.1 Batteries included: Rust’s tooling 1.2 The Rust compiler 1.3 Rust for web services 1.4 Maintainability of Rust applications 2 Laying the foundation 2.1 Following the Rust playbook Modeling your resources with structs Understanding options Using documentation to solve errors Handling strings in Rust Taking an excursion into moving, borrowing, and ownership Using and implementing traits Handling results 2.2 Creating our web server Handling multiple requests at once
📄 Page
10
Rust’s asynchronous environment Rust’s handling of async/await Using Rust’s Future type Choosing a runtime Choosing a web framework Part 2 Getting started 3 Create your first route handler 3.1 Getting to know our web framework: Warp What is included in Warp Warp’s filter system 3.2 GET your first JSON response Align with your framework’s way of thinking Handle the success route Get help from Serde Handle errors gracefully 3.3 Handling CORS headers Returning CORS headers on the application level Testing CORS responses 4 Implement a RESTful API 4.1 GET questions from in-memory Setting up a mock database Preparing a set of test data Reading from the fake database Parsing query parameters Returning custom errors 4.2 POST, PUT, and DELETE questions Updating our data in a thread-safe way Adding a question
📄 Page
11
Updating a question Handling malformed requests Removing questions from the storage 4.3 POST answers via url-form-encoded Difference between url-form-encoded and JSON Adding answers via url-form-encoded 5 Clean up your codebase 5.1 Modularizing your code Using Rust’s built-in mod system Practical folder structure for different use cases Creating libraries and sub-crates 5.2 Documenting your code Using doc comments and private comments Adding code in your comments 5.3 Linting and formatting your codebase Installing and using Clippy Formatting your code with Rustfmt 6 Logging, tracing, and debugging 6.1 Logging in your Rust application Implementing logging in your web service Logging incoming HTTP requests Creating structured logs 6.2 Tracing in asynchronous applications Introducing the Tracing crate Integrating tracing in our application 6.3 Debugging Rust applications Using GDB on the command line Debugging our web service with LLDB Using Visual Studio Code and LLDB
📄 Page
12
7 Add a database to your application 7.1 Setting up our example database 7.2 Creating our first tables 7.3 Working with a database crate Adding SQLx into our project Connecting Store to our database 7.4 Reimplementing our route handlers Adding the database to get_questions Reimplementing the add_question route handler Adjusting the update and delete questions handler Updating the add_answer route 7.5 Error handling and tracing database interactions 7.6 Integrating SQL migrations 7.7 Case study: Switching database management systems 8 Integrate third-party APIs 8.1 Preparing the codebase Picking an API Getting to know our HTTP crate Adding an example HTTP call with Reqwest Handling errors for external API requests 8.2 Deserializing JSON responses to structs Gathering API response information Creating types for our API responses 8.3 Sending questions and answers to the API Refactoring the add_question route handler Making profanity checks for updating questions Updating the add_answer route handler 8.4 Handling timeouts and multiple requests at once
📄 Page
13
Implementing a retry for external HTTP calls Executing futures concurrently or in parallel Part 3 Bring it into production 9 Add authentication and authorization 9.1 Adding authentication to our web service Creating the user concept Migrating the database Adding the registration endpoint Hashing the password Handling duplicate account errors Stateful vs. stateless authentication Adding the login endpoint Adding an expiry date to tokens 9.2 Adding authorization middleware Migrating the database tables Creating token validation middleware Extending existing routes to handle account IDs 9.3 What we didn’t cover 10 Deploy your application 10.1 Setting up your application through environment variables Set up config files Accept command-line inputs for your application Read and parse environment variables into your web service 10.2 Compiling your web service for different environments Development vs. release flag when building your binary Cross-compile your binary for different environments 10.3 Using build.rs in your build process
📄 Page
14
10.4 Creating the right Docker image for your web service Create a statically linked Docker image Set up a local Docker environment with docker-compose Extract the configuration of the web server into a new module 11 Testing your Rust application 11.1 Unit testing our business logic Testing the pagination logic and dealing with custom errors Testing the Config module with environment variables Testing the profanity module with a newly created mock server 11.2 Testing our Warp filters 11.3 Creating an integration testing setup Splitting up the codebase into a lib.rs and a binary Creating the integration-test crate and the oneshot server implementation Adding the registration test Unwinding in case of an error Testing the login and posting questions appendix A Thinking about security index
📄 Page
15
front matter preface I am a pragmatist at heart. My introduction to programming was inspired by a neighbor in my small hometown, who sold websites for businesses for a (back then) large sum of money. I thought, if he can earn money with that, I can do it, too. I started a business at the age of 17 with a friend, and we built websites for companies. Seeing this amount of value unlocked for these companies from the comfort of my home made me fall in love with this industry. However, programming was never my favorite subject, never something I wanted to dive deep into. It was a means to an end, something I had to do so I could deliver an application or a website. I went from writing PL/I on the mainframe to JavaScript for browser applications, while doing backend APIs in between. I just love developing for the internet. This passion led to Rust. It’s the first time a language and its compiler had my back so I could focus on what’s important: creating value for others. Rust Web Development is written from this pragmatic view about our industry: creating value with the best tools currently available. This book shows why Rust, even if not obvious at first sight, is a perfect match for the future generation of web applications and APIs. Rust Web
📄 Page
16
Development is not just about syntax, but offers guidance and deep dives, and enables you to confidently start and finish your next project with Rust. I want to lift the curtain and look behind the scenes of a Rust crate, the language itself, and of the web frameworks we choose. The level of detail will always aim to be pragmatic: how much do you need to know to make a difference, to understand a solution so you can adapt it in your own project, and let you know where to look further. To quote one of my former colleagues, “Writing Rust is like cheating!” My hope is that this book inspires you to see the beauty of developing for the web, with a language that has your back and empowers you to do things faster and safer than you could have done before. I am honored to take you on this journey! acknowledgments First, I have to thank my wife, Emily, for believing in me, pushing me forward, and never giving up on trusting that I could finish this book. Writing this book took a lot of hours away from our already limited time, and I will be forever grateful for your support. Thank you for always having my and our family’s backs. I love you. Next, I have to thank Mike Stephens, for reaching out to me and making this book happen. The first calls with you were truly inspiring and made me believe that I could actually
📄 Page
17
write a book. Your wisdom and experience influenced this book and my writing for years to come. To my editor at Manning, Elesha Hyde: thank you for your patience, your input, your constant following up with emails and invaluable suggestions and guidance throughout this journey. I always looked forward to our meetings and I will truly miss them. Thank you to the developers who inspired me on this journey: Mariano, your wisdom and insights carried me not only through this book but also through a good chunk of my developer career. Knut and Blake, our time at smartB and the discussions afterward shaped the way I approached the readers of this book. Simon, you taught me a lot about what it takes to be a developer and take one’s craft seriously. And thank you, Paul, for providing an outlet, recharging my energy, and getting me excited about our craft through our conversations. Dada, studying together with you was one big cornerstone of being able to write this book. And last but not but least, Sebastian and Fernando, our time together shaped me more than anything else to be the developer and person I am today. To all the reviewers: Alain Couniot, Alan Lenton, Andrea Granata, Becker, Bhagvan Kommadi, Bill LeBorgne, Bruno Couriol, Bruno Sonnino, Carlos Cobo, Casey Burnett, Christoph Baker, Christopher Lindblom, Christopher Villanueva, Dane Balia, Daniel Tomás Lares, Darko Bozhinovski, Gábor László Hajba, Grant Lennon, Ian Lovell, JD McCormack, Jeff Smith, Joel Holmes, John D. Lewis, Jon
📄 Page
18
Riddle, JT Marshall, Julien Castelain, Kanak Kshetri, Kent R. Spillner, Krzysztof Hrynczenko, Manzur Mukhitdinov, Marc Roulleau, Oliver Forral, Paul Whittemore, Philip Dexter, Rani Sharim, Raul Murciano, Renato Sinohara, Rodney Weis, Samuel Bosch, Sergiu Răducu Popa, Timothy Robert James Langford, Walt Stoneburner, William E. Wheeler, and Xiangbo Mao; your suggestions helped make this a better book. about this book Rust Web Development will help you write web applications (be it an API, a microservice, or a monolith) from start to finish. You’ll learn everything you need to open an API to the outside world, connect a database to store your data, and test and deploy your application. This is not a reference book; it should be considered a workbook. The application we are building will make sacrifices in its design so concepts can be taught at the right time. It takes the whole book to finally be able to ship it to production. Who should read this book This book is for people who have read the first six chapters of The Rust Programming Language by Steve Klabnik and Carol Nichols (No Starch Press, 2019) and then asked themselves, “What can I do with that?” It is also meant for developers who have built web applications in the past with
📄 Page
19
a different language and are wondering if Rust would be a good choice for their next project. And last, it is a great book to help onboard yourself or a new hire to a new job requiring you to write and maintain web applications in Rust. How this book is organized: A road map Rust Web Development has three parts with 11 chapters and one appendix. Part 1 covers the why and how of writing Rust: Chapter 1 covers for which environment and team Rust is a great fit and explains the mindset behind choosing Rust for your team or next project. It compares the language with others and gives a sneak peek into its web ecosystem. Chapter 2 talks about the Rust language foundations and knowledge needed to complete the book and understand the code snippets presented. It also covers the web ecosystem foundations and explains the extra tooling needed to write asynchronous applications in Rust. Part 2 is about creating the business logic of the application:
📄 Page
20
Chapter 3 creates the foundation that we will build on later in the book. It introduces Warp, the web framework we are using, and how to respond to HTTP GET requests with JSON. Chapter 4 covers HTTP POST, PUT, and DELETE requests and how to read fake data from in-memory. This chapter also covers the differences between url-form- encoded and JSON bodies. Chapter 5 is all about modularizing, linting, and formatting your code. We split large chunks of code into their own modules and files, use the Rust commenting system to annotate our codebase, add linting rules, and format it. Chapter 6 introspects your running application. We explain the difference between logging and tracing and show various ways of debugging your code. Chapter 7 gets rid of the in-memory storage and adds a PostgreSQL database instead. We connect to a database on localhost and go through the process of creating a connection pool and sharing it among our route handlers. Chapter 8 connects to an external service, where we send data and process the received answer. We discuss how to bundle asynchronous functions and deserialize JSON responses. Part 3 makes sure everything is ready to bring your code in production.
The above is a preview of the first 20 pages. Register to read the complete e-book.
Recommended for You
Loading recommended books...
Failed to load, please try again later