Share E-Book
Scan to open this page

Scan with your phone to open this page

Author: Alex Edwards

Rating No ratings yet

Last updated 2025-02-13 15:56:01 UTC. Version 2.24.0. Let’s Go teaches you step-by-step how to create fast, secure and maintainable web applications using the fantastic programming language Go. The idea behind this book is to help you learn by doing. Together we’ll walk through the start-to-finish building of a web application — from structuring your workspace through to session management, authenticating users, securing your server and testing your application. Building a complete web application in this way has several benefits. It helps put the things you’re learning into context, it demonstrates how different parts of your codebase link together, and it forces us to work through the edge-cases and difficulties that come up when writing software in real-life. In essence, you’ll learn more than you would by just reading Go’s (great) documentation or standalone blog posts. By the end of the book you’ll have the understanding and confidence to build your own production-ready web applications with Go. Although you can read this book cover-to-cover, it’s designed specifically so you can follow along with the project build yourself.

AI Reading Assistant

Whole-book reading guide from stratified index samples; jump to passages in the text

AI guide
【One-Line Pitch】 A hands-on, project-driven guide that walks you through building a complete, production-ready web application in Go—covering everything from project structure and routing to database integration, authentication, and testing. Ideal for developers with basic Go knowledge who want to move from tutorials to real-world, maintainable web apps. 【Book Arc】 - **Opening (~0%–9%)**: Sets up the "Snippetbox" project—a simple note-sharing app—and covers the fundamentals of Go's `net/http` package, including creating a server, defining handlers, and using the built-in servemux for routing. You'll learn about URL pattern matching, path sanitization, and how to customize HTTP responses with status codes and headers. - **Early (~9%–25%)**: Introduces HTML templating with Go's `html/template` package, showing how to create reusable layouts with named templates and pass dynamic data. This section also covers serving static files, the `http.Handler` interface, and the `HandlerFunc` adapter, plus the importance of structured logging for debugging and monitoring. - **Early (~25%–34%)**: Focuses on database integration with MySQL. You'll learn how to set up a database, create a restricted user, and use `database/sql` to manage connection pools. The section emphasizes writing clean, maintainable code by encapsulating database operations in a model layer and creating helper functions for consistent error handling. - **Middle (~34%–47%)**: Dives deeper into the model layer, demonstrating how to build a `SnippetModel` with methods like `Get` and `Latest` for querying data. You'll see how to handle `sql.ErrNoRows` errors gracefully, use prepared statements for efficiency and security, and pass data from models to templates via a `templateData` struct. The section also covers adding common dynamic data (like the current year) to all pages. - **Middle (~47%–end)**: Continues with advanced templating techniques, including custom template functions and pipelining data. The book then moves into more complex topics like session management, user authentication, securing the server, and testing the application—all within the context of the ongoing Snippetbox project. 【Key Takeaways】 - **The servemux is your router** (Early): Go's `http.NewServeMux()` provides a clean, built-in way to handle routing. You can register handlers with method-specific patterns like `"GET /snippet/view/{id}"`, and the servemux automatically handles URL sanitization and trailing-slash redirects, reducing boilerplate and potential bugs. - **Handlers are just functions** (Early): Any function with the signature `func(w http.ResponseWriter, r *http.Request)` can be turned into an `http.Handler` using `http.HandlerFunc()`. This simplicity makes it easy to write and test handlers, and you can chain them to add middleware-like behavior. - **Encapsulate your data layer** (Early): Instead of scattering SQL queries throughout your handlers, create a dedicated model layer (e.g., `SnippetModel`) with methods like `Get` and `Latest`. This keeps your code organized, testable, and makes it easy to swap databases or mock the model for unit tests. - **Use connection pools wisely** (Early): `sql.Open()` returns a `sql.DB` object that manages a pool of connections. Always close result sets with `defer rows.Close()` to avoid exhausting the pool, and use prepared statements for repeated queries to improve performance and prevent SQL injection. - **Templates are powerful and safe** (Middle): Go's `html/template` package automatically escapes HTML, protecting against XSS attacks. Use named templates (`{{define "base"}}`) and actions like `{{template "main" .}}` to create reusable layouts, and pass data via a `templateData` struct to keep your templates clean. - **Centralize error handling** (Early): Create helper methods like `serverError()` and `clientError()` to log errors with context (method, URI) and send appropriate HTTP status codes. This reduces code duplication and ensures consistent, user-friendly error responses. - **Structure your project for growth** (Early): Organize your code into `cmd/web` for the application entry point and `internal/models` for business logic. This separation of concerns makes the codebase easier to navigate, test, and maintain as the project grows. 【Reading Tips】 - **Follow along with the build**: The book is designed for hands-on learning. Set up the Snippetbox project and code along with each chapter—you'll retain much more than by just reading. - **Skim the "Additional information" boxes**: These contain useful tips and edge cases (like wildcard routing and pipelining) but can be read quickly if you're focused on the main flow. - **Deep-read the database chapters**: The sections on `database/sql`, connection pools, and model design are foundational. Pay close attention to error handling and prepared statements—these are critical for production apps. - **Don't skip the templating chapters**: Go's template syntax has unique quirks (like the dot notation for data). Understanding named templates and how to pass data will save you hours of debugging later. - **Use the HTML version**: If you're coding along, the HTML version of the book preserves code formatting, making it easy to copy-paste snippets without errors. 【Coverage Limits】 This guide covers the core web development topics in the excerpts (routing, templating, database integration, and error handling). The later sections on session management, authentication, and testing are mentioned but not detailed in the provided material.
Page 8
r 10 years, building production applications for myself and commercial clients, and helping people all around the world improve their Go skills. You can see...
View in text
Excerpt 2
n :4000") err := http.ListenAndServe(":4000", mux) log.Fatal(err) } Once that’s complete, restart the application and open http://localhost:4000/static/ in y...
View in text
Excerpt 3
are a few things about this code to explain and emphasize: The first parameter to sql.Open() is the driver name and the second parameter is the data source n...
View in text
Excerpt 4
| id < 1 { http.NotFound(w, r) return } snippet, err := app.snippets.Get(id) if err != nil { if errors.Is(err, models.ErrNoRecord) { http.NotFound(w, r) } el...
View in text
Excerpt 5
["title"] = "This field cannot be blank" } else if utf8.RuneCountInString(form.Title) > 100 { form.FieldErrors["title"] = "This field cannot be more than 100...
View in text
Excerpt 6
he connection, the user won’t receive any HTTP(S) response. Setting a short ReadTimeout period helps to mitigate the risk from slow-client attacks — such as...
View in text
Excerpt 7
e previous chapter, we can check whether a request is being made by an authenticated user or not by checking for the existence of an "authenticatedUserID" va...
View in text
Excerpt 8
When you visit https://localhost:4000 in your browser, the static files should be served from the embedded filesystem and everything should look normal. Chap...
View in text
Tags
AI categories
Programming LanguageGoBackend
Publisher: alexedwards.net
Publish Year: 2025
Language: English
Pages: 441
File Format: PDF
File Size: 7.5 MB
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.

Generating text preview…