Share E-Book
Scan to open this page

Scan with your phone to open this page

AuthorAlex Edwards

Let's Go Further guides you through the start-to-finish build of a modern JSON API in Go – from project setup to deployment in production. As well as covering fundamental topics like sending and receiving JSON data, the book goes in-depth and explores practical code patterns and best practices for advanced functionality like implementing graceful shutdowns, managing background tasks, reporting metrics, and much more. You’ll learn a lot about topics that are often important to your real-world work, but which are rarely discussed in beginner-level courses and aren't fully explained by the official Go documentation. Let's Go Further also goes beyond development. It outlines tools and techniques to help manage your project on an ongoing basis, and also gives you a step-by-step playbook for deploying your API to a live production server. By the end of the book you'll have all the knowledge you need to create robust and professional APIs which act as backends for SPAs and native mobile applications, or function as stand-alone services. If you read and enjoyed the first Let’s Go book, this course should be a great fit for you and an ideal next step in mastering Go.

AI Reading Assistant

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

AI guide
# Let's Go Further: Advanced Patterns for Building APIs and Web Applications in Go ## 【One-Line Pitch】 A hands-on, project-driven guide to building production-ready JSON APIs in Go, covering everything from RESTful routing and database integration to graceful shutdowns and deployment — ideal for developers who've completed a Go basics course and want to master real-world backend patterns. ## 【Book Arc】 - **Opening (~0%–10%)**: Sets up the "Greenlight" movie API project — directory structure, HTTP server setup, command-line flag configuration, dependency injection, and RESTful routing with the httprouter package. - **Early (~10%–25%)**: Focuses on JSON fundamentals — writing JSON responses with custom struct tags (`omitempty`, `-`), implementing `MarshalJSON()` for advanced customization, and robust JSON decoding with error handling for malformed input, unknown fields, and oversized bodies. - **Early-Middle (~25%–40%)**: Introduces input validation with reusable validation rules, connects to PostgreSQL using the `pq` driver, and establishes a connection pool with sensible configuration (MaxOpenConns, MaxIdleConns, ConnMaxIdleTime). - **Middle (~40%–55%)**: Builds out the full CRUD API — creating, reading, updating, and deleting movie records — with SQL queries, `pq.Array()` for PostgreSQL arrays, and custom error handling for record-not-found cases. - **Middle-Late (~55%–75%)**: Addresses concurrency concerns with optimistic locking using version numbers, and covers advanced topics like graceful shutdowns, background task management, and metrics reporting. - **Late-Ending (~75%–100%)**: Covers production deployment — database migrations, server configuration, and a step-by-step playbook for deploying the API to a live server. ## 【Key Takeaways】 - **RESTful routing with method-based dispatch** (Early): Using appropriate HTTP methods (GET, POST, PUT, DELETE) for different actions on the same URL pattern ensures semantic correctness and security — a foundational pattern for any API design. - **Struct tags for JSON control** (Early): The `omitempty` directive hides empty fields while `-` permanently excludes sensitive or internal data from JSON output — essential for clean, secure API responses. - **Custom JSON encoding via `MarshalJSON()`** (Early): Implementing the `json.Marshaler` interface gives you complete control over how types are serialized, enabling custom formats that struct tags alone can't achieve. - **`json.Decoder` beats `json.Unmarshal` for performance** (Early): Benchmark results show the Decoder approach uses ~80% less memory and is slightly faster — a meaningful optimization for high-traffic APIs. - **Robust error handling for JSON decoding** (Early): Using `errors.As()` and `errors.Is()` to distinguish syntax errors, type mismatches, unknown fields, and empty bodies produces clear, actionable error messages for API clients. - **Reusable validation functions** (Early): Keeping validation logic close to domain types (e.g., `ValidateMovie()` in the `internal/data` package) prevents duplication and makes validation testable and maintainable. - **Connection pool tuning matters** (Early): Setting appropriate `MaxOpenConns`, `MaxIdleConns`, and `ConnMaxIdleTime` values prevents resource exhaustion and stale connections — a critical but often-overlooked production concern. - **Optimistic locking prevents lost updates** (Middle): Using a version number that increments on each update detects concurrent modifications, preventing silent data loss when multiple clients edit the same record. ## 【Reading Tips】 - **Skim the early setup chapters** (~0%–10%) if you've already built a basic Go web server — the routing and configuration patterns are standard, but the dependency injection approach is worth a quick read. - **Deep-read the JSON customization sections** (~10%–25%): The `MarshalJSON()` implementation and error-handling patterns are the most transferable skills in the book — study the code carefully and adapt it to your own projects. - **Pay special attention to the concurrency chapter** (~48%): The optimistic locking example with `pg_sleep(10)` clearly demonstrates the lost-update problem and its solution — this is where the book earns its "advanced" title. - **Don't skip the deployment sections** (~75%+): Even if you're not deploying immediately, the migration workflow and production configuration patterns are valuable reference material for future projects. - **Code along with the Greenlight project**: The book is structured as a continuous build — typing out the code and running the examples will cement the patterns far better than reading alone. ## 【Coverage Limits】 This guide covers the book's core progression from project setup through CRUD operations, JSON handling, and database integration. The excerpts do not fully cover the later chapters on graceful shutdowns, background tasks, metrics, and deployment specifics — these are mentioned in the book's overview but not detailed in the source material. ##
Excerpt 1
I endpoints. Chapter 2.3. API Endpoints and RESTful Routing Over the next few sections of this book we’re going to gradually build up our API so that the end...
View in text
Excerpt 2
e is actually a struct, but it has a MarshalJSON() method which outputs a RFC 3339 format representation of itself. This is what gets called whenever a time....
View in text
Excerpt 3
driver you’re using (and should be described in the driver documentation), but when using pq you should be able to connect to your local greenlight database...
View in text
Excerpt 4
query to delete the record in our database is also simple: DELETE FROM movies WHERE id = $1 In this case the SQL query returns no rows, so it’s appropriate f...
View in text
Excerpt 5
"year": 2018, "runtime": "134 mins", "genres": [ "sci-fi", "action", "adventure" "version": 2 } ] } In contrast, using a sort parameter of descending runtime...
View in text
Excerpt 6
pi/server.go package main import ( "fmt" "net/http" "os" // New import "os/signal" // New import "syscall" // New import "time" ) func (app *application) ser...
View in text
Excerpt 7
application struct { config config logger *jsonlog.Logger models data.Models mailer mailer.Mailer wg sync.WaitGroup } Next let’s head to the cmd/api/helpers....
View in text
Excerpt 8
dator.New() data.ValidateEmail(v, input.Email) data.ValidatePasswordPlaintext(v, input.Password) if !v.Valid() { app.failedValidationResponse(w, r, v.Errors)...
View in text
Tags
AI categories
BackendGoProgramming
Publisher: alexedwards.net
Publish Year: 2021
Language: English
Pages: 584
File Format: PDF
File Size: 7.7 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…