Learn Go with Pocket-Sized Projects (Final) (Aliénor Latour, Donia Chaiehloudj etc.)(Z-Library)
code
No Description
180
Views
0
Downloads
0.00
Total Donations
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
Learn Go with Pocket-Sized Projects Aliénor Latour, Donia Chaiehloudj, and Pascal Bertrand To comment go to livebook. Manning Shelter Island For more information on this and other Manning titles go to manning.com.
Page
3
copyright For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book 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 © 2025 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.
Page
4
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 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 PO Box 761 Shelter Island, NY 11964 The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. ISBN 9781633438804 Printed in the United States of America Development editor: Doug Rudder Technical editor: Egon Elbre Review editors: Dunja Nikitović and Aleksandar Dragosavljević Production editor: Keri Hales Copy editor: Julie McNamee
Page
5
Proofreader: Katie Tennant Technical proofreader: Mike Haller Typesetter: Tamara Švelić Sabljić Cover designer: Marija Tudor
Page
6
dedication To Pulsar, that brought us together, and tea time, that keeps us together —Aliénor To Didier, Lila, my mum, and all the gophers —Donia To my parents, who nurtured in me a love for books —Pascal
Page
7
contents foreword preface acknowledgments about this book about the authors about the cover illustration 1 Meet Go 1.1 What is Go? 1.2 Why you should learn Go 1.2.1 How and where Go can help you 1.2.2 Where can Go cannot help you 1.2.3 Comparison with commonly used languages 1.3 Why pocket-sized projects? 1.3.1 What you’ll know after reading the book (and writing the code) 2 Hello, earth! Extend your hello, world 2.1 Any travel begins at home 2.1.1 Our first program: main.go 2.1.2 Let’s test with the Example function 2.1.3 Calling the greet function 2.1.4 Testing a specific function with the testing package 2.2 Are you a polyglot?
Page
8
2.2.1 Parlez-vous français? The switch angle 2.2.2 Adapt the test with Test functions 2.3 Supporting more languages with a phrasebook 2.3.1 Introducing the Go map hash table 2.3.2 Writing a table-driven test 2.4 Using the flag package to read the user’s language 2.4.1 Add a flag 2.4.2 Test the command-line interface 2.5 Side quests 3 A bookworm’s digest: Playing with loops and maps 3.1 Loading the JSON data 3.1.1 Defining a JSON example 3.1.2 Opening a file 3.1.3 Parse the JSON 3.1.4 Test it 3.2 Finding books that bookworms have in common 3.2.1 Count the books 3.2.2 Keeping higher occurrences 3.2.3 Determinism 3.3 Print 3.4 Improvements 3.4.1 Implement sort.Interface 3.4.2 Exercise: Reading recommendations 3.4.3 Using bufio to open a file 4 A log story: Creating a library 4.1 Defining the API
Page
9
4.1.1 Package summary 4.1.2 Exporting the supported levels 4.1.3 Object-oriented Go: “GoOOP”? 4.1.4 The New() function 4.1.5 What about testing? 4.1.6 Documenting code 4.2 Implementing the exported methods 4.2.1 Default implementation 4.2.2 Interfacing 4.2.3 Refactoring 4.3 The functional options pattern 4.3.1 Creating configurations 4.3.2 Testing our example 4.4 Additional functionalities 4.4.1 Logging the log level 4.4.2 Exposing the generic logging function 4.5 Logging: Best practices 5 Gordle: Play a word game in your terminal 5.1 Basic main version 5.1.1 Mini main 5.1.2 Read player’s input 5.1.3 Isolate the check 5.1.4 Check for victory 5.2 Providing feedback 5.2.1 Define character status 5.2.2 Checking a guess against the solution
Page
10
5.3 Corpus 5.3.1 Create a list of words 5.3.2 Read the corpus 5.3.3 Pick a word 5.3.4 Let’s play! 5.4 The limit of runes 5.5 Conclusion 6 Money converter: CLI around an HTTP call 6.1 Business definitions 6.1.1 Converting money 6.2 Representing money 6.2.1 Floating-point numbers 6.2.2 Back to money 6.2.3 Floating-point number operations 6.2.4 Implementing decimals 6.2.5 Currency value object 6.2.6 NewAmount 6.3 Applying conversion logic 6.3.1 Applying an exchange rate 6.3.2 Validating the result 6.4 Writing the CLI 6.4.1 Flags and arguments 6.4.2 Parse into business types 6.4.3 Stringer 6.4.4 Convert 6.5 Calling the bank
Page
11
6.5.1 Dependency injection: Theory 6.5.2 ECB package 6.5.3 HTTP call: Easy version 6.5.4 Parse the response 6.5.5 Integration in the money package 6.5.6 Dependency injection in main 6.5.7 Sharing the executable 6.6 Making improvements 6.6.1 Caching 6.6.2 Timeout 6.6.3 Alternative tree 7 Caching with generics 7.1 A naive cache 7.1.1 Introduction to generics 7.1.2 Project initialization 7.1.3 Implementation 7.2 Introducing goroutines 7.2.1 What’s a goroutine? 7.2.2 How to launch a goroutine 7.2.3 Using channels to communicate that a goroutine has ended 7.2.4 Running goroutines and having a synchronization point 7.3 A more thread-safe cache 7.3.1 Using goroutines 7.3.2 Using t.Parallel() 7.3.3 Using go test -race . 7.3.4 Add a mutex
Page
12
7.4 Possible improvements 7.4.1 Adding time to live 7.4.2 Add a maximum number of items in the cache 7.5 Common mistakes 7.5.1 When to use channels in a concurrency situation 7.5.2 Concurrency effect of a workload type 7.5.3 Finish your goroutines 8 Gordle as a service 8.1 Empty shell for the new service 8.1.1 Server, service, web service, endpoints, and HTTP handlers 8.1.2 Let’s code 8.2 Adding endpoints 8.2.1 Create a new game 8.2.2 Get the game status 8.2.3 Guess 8.3 Domain objects 8.3.1 Domain types 8.3.2 API adapters 8.4 Repository 8.4.1 In-memory database 8.4.2 Simplest repository 8.4.3 Service-level dependency 8.4.4 Add a mutex to the repository 8.5 Adapting the Gordle library 8.5.1 API of the library 8.5.2 Usage in the endpoints
Page
13
8.6 Security notions and improvements 8.6.1 Limiting the number of requests served at a time 8.6.2 User authentication 8.6.3 Logging 8.6.4 Error formatting 8.6.5 Decode query parameters 9 Concurrent maze solver 9.1 Maze generation 9.1.1 What is an image? 9.1.2 Maze constraints 9.2 Maze solver 9.2.1 Setup 9.2.2 Loading the maze image 9.2.3 Add the solver 9.3 Let’s go exploring! 9.3.1 Finding the entrance 9.3.2 Communicating new possible paths 9.3.3 Recording the explored path 9.3.4 Waiting for unexplored paths and starting a goroutine 9.3.5 Stop listening, we found it: Short version 9.3.6 Testing one goroutine’s logic 9.4 Show the result 9.5 Notify when the treasure is found 9.5.1 Keep track of all the goroutines 9.5.2 Send a quit signal 9.6 Visualization
Page
14
9.6.1 Overcome the loop constraint 9.6.2 Animate the exploration 10 Habits tracker using gRPC 10.1 API definition 10.1.1 Protobuf declaration 10.1.2 Code generation 10.2 Empty service 10.2.1 Creating a small logger 10.2.2 Server structure 10.2.3 Creating and running the server 10.3 First endpoint: Create 10.3.1 Business layer 10.3.2 API layer 10.3.3 Data retention 10.4 Unit testing with generated mocks 10.4.1 Generate mocks 10.4.2 Use the mocks 10.5 Integration testing 10.5.1 List habits 10.5.2 Integration with go test 10.6 Getting the best out of the context 10.6.1 What is a context? 10.6.2 Create a context 10.6.3 Using a context 10.7 Track your habits 10.7.1 Tick a habit
Page
15
10.7.2 Store ticks per week 10.7.3 Handle corner cases 10.7.4 Get habit status 10.7.5 Add a timestamp 10.7.6 Habit tracker in action 11 HTML templating with a gRPC client 11.1 Your basic HTTP server 11.1.1 Hello plain text 11.1.2 Templates: Display a variable 11.1.3 Add a gRPC client 11.2 Basic template operations 11.2.1 Iterate through a slice 11.2.2 Accessing fields 11.2.3 Conditional formatting 11.3 Send a tick to the server 11.3.1 What page should we display? 11.3.2 Send tick to the backend 11.3.3 Adding colors 11.4 Use a form to create a habit 11.4.1 HTML form 11.4.2 Read a form’s values 11.5 More template niceties 11.5.1 Passing more than one object to the template 11.5.2 Calling functions 11.5.3 Using define to declare functions 12 Go for other architectures
Page
16
12.1 Getting started with Wasm 12.1.1 Some practice with Hello Wasm 12.1.2 Write a file server 12.2 Multiplication quiz project 12.2.1 Displaying random numbers on the HTML page 12.2.2 Registering functions in Go 12.2.3 Reading an input from the page 12.3 TinyGo 12.3.1 Building a simple TinyGo application 12.3.2 Differences with Go 12.3.3 Debugging and deploying with TinyGo appendix A Installation steps A.1 Install A.2 Check A.3 Go’s environment variables A.3.1 The go env command A.3.2 The GOBIN variable A.3.3 The GOPATH variable A.3.4 The GOROOT variable A.4 Hello! A.5 Installing new dependencies A.5.1 go install A.5.2 go get A.6 Code editors appendix B Formatting cheat sheet appendix C Zero values
Page
17
C.1 What is a zero value? C.2 The zero values of any types C.3 Slices and maps specificities C.4 Benefiting from zero values appendix D Benchmarking appendix E Passing by value or by reference E.1 Go passes everything by value E.1.1 Copying parameters on the stack E.1.2 Using pointers E.1.3 Shallow copies E.1.4 Functions vs. methods E.2 Special types of parameters: slices, maps, and channels E.2.1 Passing a slice as a parameter E.2.2 maps, channels, and more E.3 A few recommendations E.3.1 Passing by value should be the default E.3.2 Passing by pointer is a minor optimization E.3.3 Passing by pointer when mutating E.3.4 Using slices and maps E.3.5 Passing a pointer to a slice or to a map E.3.6 Writing your own Copy function appendix F Fuzzing F.1 A new testing method F.2 How it works F.3 Writing a first test F.3.1 Function under test
Page
18
F.3.2 Fuzz test F.4 Running and interpreting fuzz tests F.5 Fixing the breach F.6 Best practices and common pitfalls appendix G Connecting to a database G.1 Setup G.1.1 Starting a PostgreSQL database locally G.1.2 Seed the schema G.2 Repository package G.2.1 Injecting a connection G.2.2 Querying the database G.3 Libraries index
Page
19
foreword Programming is for everyone. This dream of making computers available and easier to use has been one of the guiding principles for so many pioneers in this still evolving field. We are the inheritors of this fantastic legacy. And by we, of course, I mean you and I, the generations of people who have been able to follow some of the many paths to computer use that have already been prepared for us, in particular, that collection of tools for thought known as programming languages. A few of those very smart yet practical people created the Go programming language. Go can be quite expressive, despite having a small number of keywords compared to many other popular programming languages. This makes it a lot easier to remember, but certainly doesn’t always make it obvious how to make Go do what you want, at least not without some guidance. The real trick is to make it easier for people to make some relatively quick progress toward whatever they want to achieve, while at the same time preparing them with the deeper knowledge they will need to go further. And one of the best ways to accomplish this is by way of a well-thought-out book, such as the one you’re looking at right now. Learn Go with Pocket-Sized Projects gives you practical projects that are neither too big to wrap your head around quickly, nor too small to actually show you something useful. Along the way, the book is seasoned with a number of important techniques that you’ll surely need, shared with a wry humor that keeps you smiling. Regardless if you’re a student, hobbyist, or professional practitioner, there’s something for you to grab ahold of and run with for a bit. And that is a great way to learn. The book introduces you to some among the wide spectrum of possibilities that Go can be used for. From an elaborated hello, world, to making LEDs
Page
20
blink on an Arduino, it contains a nice collection of different small applications to help you feel full but not overstuffed. Most importantly, the book does so with a sense of fun and playfulness. Learning doesn’t happen when you’re bored out of your mind; it happens when you are fully engaged. Grasping this simple truth and using it to write a book about Go programming just seems like a good idea, and I’m glad to see that my friends have done exactly that. —Ron Evans, Open Source Contributor, TinyGo, and Technologist for Hire, The Hybrid Group
The above is a preview of the first 20 pages. Register to read the complete e-book.
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
【One-Line Pitch】
Learn Go by building 12 small, practical projects—from a CLI greeting tool to a gRPC habit tracker and WebAssembly experiments—perfect for busy developers who want hands-on experience with real-world Go patterns, testing, and architecture.
【Book Arc】
- **Opening (~0%–10%)**: Introduces the book's philosophy of learning through small, timed projects, then starts with a simple CLI tool that greets users in multiple languages, teaching basic syntax, maps, and function structure.
- **Early (~10%–23%)**: Builds a bookworm CLI tool that parses JSON book collections, teaching file I/O, JSON decoding, slices vs. arrays, and sorting—plus a logging library project that introduces interfaces, zero values, and closed-box testing.
- **Early-Middle (~23%–39%)**: Develops "Gordle," a Wordle clone, covering rune handling, string manipulation, game state management, and table-driven tests with feedback logic.
- **Middle (~39%–48%)**: Creates a money/currency package that handles decimal precision (avoiding float issues) and fetches exchange rates via HTTP, teaching custom types, error handling, and testing HTTP calls with `httptest`.
- **Late (~48%–75%)**: Covers more advanced projects including a maze exploration tool (overcoming loop constraints, animation) and a gRPC-based habit tracker with Protobuf definitions, code generation, server/client architecture, and unit/integration testing with mocks.
- **Ending (~75%–100%)**: Explores WebAssembly and TinyGo for edge/embedded environments, with appendices on benchmarking, fuzz testing, and database connections.
【Key Takeaways】
- **Learning by doing is the core method** (Early): Each chapter is a self-contained project designed to be completed in a short session, reinforcing concepts through immediate application rather than abstract theory.
- **Slices over arrays in practice** (Early): Arrays have fixed lengths baked into their type, making them inflexible; slices provide dynamic views and are the idiomatic choice for most Go code.
- **JSON handling requires exported fields** (Early): The `encoding/json` package can only decode into exported struct fields, and using `json.Decoder` with `io.Reader` is preferred over `json.Unmarshal` for streaming data.
- **Table-driven tests are a Go best practice** (Early): Structuring tests as maps of cases with expected outcomes makes them readable, maintainable, and easy to extend—as shown in the Gordle feedback tests.
- **Custom types hide implementation details** (Middle): The money package exposes a `Decimal` type while keeping internal representation private, allowing refactoring without breaking the API—a key design principle.
- **Error handling is explicit and deliberate** (Middle): Go uses sentinel errors and error propagation as the primary mechanism for handling failures, with functions returning errors as their last return value.
- **Testing HTTP calls requires mocking** (Middle): The `httptest` package provides a lightweight server for testing HTTP-dependent code without making real network calls, keeping unit tests fast and reliable.
- **Contexts manage request lifecycle** (Late): The gRPC habit tracker demonstrates how `context.Context` carries deadlines, cancellations, and values across API boundaries, essential for production services.
【Reading Tips】
- **Skim the theory sections** (Early): The book weaves in language fundamentals alongside projects; if you're already comfortable with Go basics, focus on the project code and skip ahead to the "why" discussions.
- **Deep-read the testing chapters** (Early–Middle): Testing is a recurring theme—from closed-box testing to table-driven tests and mock generation—so pay close attention to how tests are structured and why.
- **Watch for the "Side Quests"** (Early): These small exercises reinforce concepts and often introduce useful tips (like emoji insertion shortcuts); they're worth doing even if you skip other parts.
- **Type out the code yourself** (All): The authors emphasize writing code manually rather than copying; this builds muscle memory and helps you catch details the text explains.
- **Use the appendices as reference** (Ending): Benchmarking, fuzz testing, and database connections are covered in short tutorials—return to these when you need them in your own projects.
【Coverage Limits】
This guide covers the book's first half in detail (through the money/currency project and HTTP testing). Later chapters on gRPC, WebAssembly, and TinyGo are summarized from the table of contents but not deeply excerpted.
Passage locations
Excerpt 1
xed-width font like this to separate it from ordinary text. In many cases, the original source code has been reformatted; we’ve added line breaks and reworke...
View in text
Excerpt 2
at least two error cases: (1) if the indicated file doesn’t exist, and (2) if the formatting of the file is invalid. Let’s invent a file path that doesn’t ex...
View in text
Excerpt 3
the maximum number of attempts. #2 Asks for a valid word #3 We’ve exhausted the number of allowed attempts. USING EMOJIS To insert emojis, use Ctrl-Cmd-Space...
View in text
Excerpt 4
nformation, that function will be skipped.” This means that you’ll be able to see which test broke, rather than this helper function’s line number. Listing 6...
View in text
Recommended for You
{{#thumbnailUrl}}
{{/thumbnailUrl}}
{{^thumbnailUrl}}
{{/thumbnailUrl}}
Loading recommended books...
Failed to load, please try again later
Tip the Site
Scan the WeChat Pay or Alipay code to tip. No login required.
WeChat Pay
Alipay