Digital Library

Go in Practice, Second Edition (Nathan Kozyra, Matt Butcher, Matt Farina)(Z-Library)

,
,

Share E-Book

Go in Practice, Second Edition (Nathan Kozyra, Matt Butcher, Matt Farina)(Z-Library)

Author

,
,

Rating No ratings yet

Log in to rate

Go
Language English

Practical techniques for building concurrent, cloud-native, and high performance Go applications—all accelerated with productivity-boosting AI tools. Go in Practice, Second Edition is a cookbook-style collection of the techniques and best practices you need to build production-quality Go applications. It builds on your existing knowledge of the Go language, introducing specific strategies you can use to maximize your productivity in day-to-day dev work. In Go in Practice, Second Edition, you’ll learn: • Concurrency with goroutines and channels • Web servers and microservices with event streams and websockets • Logging, caching, and data access from environment variables and files • Cloud-native Go applications • AI tools to accelerate your development workflow Go in Practice, Second Edition has been extensively revised by author Nathan Kozyra to cover the latest version of Go, along with new dev techniques, including productivity-boosting AI tools. It follows an instantly-familiar cookbook-style Problem/Solution/Discussion format, building on what you already know about Go with advanced or little-known techniques for concurrency, logging and caching, microservices, testing, deployment, and more. Purchase of the print book includes a free eBook in PDF and ePub formats from Manning Publications. About the book Go in Practice, Second Edition gives you practical guidance on the ins-and-outs of Go development, covering the standard library and the most important tools from Go’s powerful ecosystem. You’ll find practical techniques for concurrency with goroutines and channels, building high-performance web services, creating effective microservices, testing and deployment, and much more. Learn how to gracefully handle errors and unexpected situations in Go, understand Go's error and panic models, and create comprehensive test suites that help prevent bugs. Plus, throughout you’ll see how you can augment your productivity by integrating AI code completion into your developm

Format PDF
Size 10.1 MB
14
Views
(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
Nathan Kozyra Matt Butcher Matt Farina M A N N I N G SECOND EDITION
Page 2
Praise for the first edition The thinking engineers guide to Go, replete with examples, pitfalls, and scalable approaches worthy of apprentices and architects alike. —Zachary Manning, senior DevOps engineer at Zillow An invaluable reference resource for Go developers seeking to refresh their knowledge of core concepts or enhance their understanding of testing, logging, and microservices. —Jonathan Reeves, software engineer at EQL Games An essential read for Go enthusiasts, offering practical tips and deep insights to harness Golang’s true potential in modern programming. —Sergio Britos Arevalo, senior software engineer at Schwarz Global Services The book to improve your Go, practically! —Leonardo Taccari, cloud architect at faire.ai
Page 3
Go in Practice, Second Edition NATHAN KOZYRA MATT BUTCHER MATT FARINA MANN I NG SHELTER ISLAND
Page 4
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 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 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. The authors and publisher have made every effort to ensure that the information in this book was correct at press time. The authors 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. Manning Publications Co. Development editor: Jeffrey Wajsberg 20 Baldwin Road Review editor: Radmila Ercegovac PO Box 761 Production editor: Andy Marinkovich Shelter Island, NY 11964 Copy editor: Keir Simpson Proofreader: Olga Milanko Technical proofreader: Joel Holmes Typesetter: Dennis Dalinnik Cover designer: Marija Tudor ISBN: 9781633436886 Printed in the United States of America
Page 5
This book is dedicated to My friends and family, who lost me for more than a few nights and weekends during the writing process Co-workers who gave support and cover along the way Colleagues and mentors who have taught and continue to teach new things daily —Nathan Kozyra
Page 6
contents preface xii acknowledgments xiv about this book xvi about the authors xx about the cover illustration xxii PART 1 BACKGROUND AND FUNDAMENTALS .....................1 1 Getting started with Go 3 1.1 What is Go? 4 1.2 Noteworthy aspects of Go 6 Multiple return values 6 ■ A modern standard library 7 Concurrency with goroutines and channels 10 ■ Go the toolchain: More than a language 14 1.3 Go in the vast language landscape 19 C and Go 20 ■ Rust, Zig, Nim, and Go 21 ■ Java and Go 22 Python, PHP, JavaScript, and Go 23 1.4 Getting up and running in Go 24 Installing Go 25 ■ Working with Git and version control 25 Exploring the workspace 25 ■ Working with environment variables 26 ■ Using artificial intelligence tools with Go 26 1.5 Hello, Go 26vii
Page 7
CONTENTSviii2 A solid foundation: Building a command-line application 29 2.1 Building CLI applications the Go way 30 Command-line flags 30 ■ Defining valid values via enums 33 Slices, arrays, and maps 35 ■ Command-line frameworks 35 2.2 Handling configuration 41 Using configuration files 42 ■ Configuration via environment variables 46 2.3 Working with real-world web servers 48 Starting up and shutting down a server 48 ■ Graceful shutdowns using OS signals 49 ■ Routing web requests 51 3 Structs, interfaces, and generics 61 3.1 Using structs to represent data 62 Creating custom data structures 62 ■ Functions inside structs 64 ■ Anonymous identifiers 66 ■ Tags in structs 67 Encoding data in JSON format 68 3.2 Contrasts with functional and object-oriented programming 69 3.3 Extending functionality with interfaces 74 3.4 Simplifying code with generics 76 Using functions with generics 79 ■ Using constraints and type approximations 81 PART 2 BUILDING ROBUST APPLICATIONS ......................85 4 Handling errors and panics 87 4.1 Error handling 88 Nil best practices 90 ■ Custom error types 93 ■ Error variables 94 4.2 Wrapping errors 96 4.3 The panic system 98 Differentiating panics from errors 98 ■ Working with panics 99 Recovering from panics 101 ■ Capturing panics with defer 102 Handling panics on goroutines 106 5 Concurrency in Go 115 5.1 Understanding Go’s concurrency model 116 5.2 Working with goroutines 117 Waiting for goroutines 118 ■ Locking with a mutex 122
Page 8
CONTENTS ix5.3 Working with channels 127 Using channels 127 ■ Closing channels 130 ■ Locking with buffered channels 135 6 Formatting, testing, debugging, and benchmarking 138 6.1 Keeping your code and projects clean 139 Keeping code well formatted 139 ■ Catching common errors with go vet 142 ■ Keeping dependencies updated 145 6.2 Logging 145 Logging data to different outputs 149 ■ Going deeper with structured logging 150 ■ Accessing and capturing stack traces 152 6.3 Unit testing in Go 154 Creating a test suit with table-driven tests 155 ■ Fuzzing test input 158 ■ Annotating tests with names 162 ■ Checking test coverage with go cover 164 ■ Wait, where is my debugger? 166 6.4 Benchmarking and performance tuning 166 7 File access and basic networking 169 7.1 Dealing with files 170 Reading files 170 ■ Writing to files 174 7.2 Basic networking via TCP 175 Logging to a network resource 176 ■ Handling back pressure in network logging 178 7.3 Basic networking with UDP 179 7.4 Websockets and server-sent events 181 Implementing websockets for real-time chat 181 ■ Server-sent events 187 PART 3 BUILDING WEB APPLICATIONS END TO END.......193 8 Building an HTTP server 195 8.1 Routing requests and accepting data 196 Routing via HTTP verbs 197 ■ More control over our server 201 8.2 Routing path values 205 Accepting POST data and query parameters 207 ■ Processing form data 209 ■ Reading and writing cookies and other header data 212 ■ Processing JSON Web Tokens 214 8.3 Generating errors and basic authentication 216
Page 9
CONTENTSx9 HTML and email template patterns 220 9.1 Working with HTML templates 221 Standard library HTML package overview 221 ■ Adding functionality inside templates 225 ■ Limiting template parsing 228 ■ When template execution breaks 229 Mixing templates 231 9.2 Using templates for email 241 10 Sending and receiving data 244 10.1 Serving static content 245 Serving subdirectories 247 ■ Using a file server with custom error pages 248 ■ Embedding files in a binary 249 ■ Serving from an alternative location 251 10.2 Advanced form processing 253 Handling form requests 253 ■ Accessing multiple values for a form field 254 ■ Working with files and multipart submissions 255 ■ Uploading multiple files 257 Verifying that uploaded file is of an allowed type 259 Saving a file incrementally 261 11 Working with external services 266 11.1 Consuming REST APIs as a full-featured client 267 Using the HTTP client 267 ■ When faults happen 269 11.2 Passing and handling errors over HTTP 273 Generating custom errors 274 ■ Reading and using custom errors 276 11.3 Parsing and mapping JSON 278 11.4 Versioning REST APIs 281 API version in the URL 282 ■ API version in content type 283 11.5 Working with gRPC 285 PART 4 GO IN THE CLOUD, MICROSERVICES, AND ADVANCED TOPICS....................................291 12 Cloud-ready applications and communications 293 12.1 Cloud computing overview 294 The types of cloud computing 294 ■ Containers and cloud-native applications 295
Page 10
CONTENTS xi12.2 Microservices and high availability 297 12.3 Communicating among services 300 Making REST faster 300 12.4 Running on cloud servers 307 Performing runtime detection 307 ■ Building for the cloud 310 12.5 Performing runtime monitoring 313 13 Reflection, code generation, and advanced Go 316 13.1 Three features of reflection 317 Switching based on type and kind 318 ■ Discovering whether a value implements an interface 322 ■ Accessing fields on a struct 325 13.2 Structs, tags, and annotations 329 Annotating structs 329 ■ Using tag annotations 330 Processing tags on a struct 331 13.3 Generating Go code with Go code 337 13.4 Working with other languages 343 index 347
Page 11
preface I started developing software at age 12 and fell in love with the craft and art of pro- gramming. Looking back nearly 30 years, it’s illuminating to see how far the industry has come and how broad it has become. A once-esoteric hobby is commonplace today. I’ve been writing code every chance I got ever since those early days and took that into undergraduate and graduate school and into the field. That I was able to take that excitement and make a career out of it is worth reflecting on periodically. Although there are a lot of things about those early days I hold with a nostalgic love—the dedicated computer room, preinternet and early internet exploration and discovery—one thing I don’t pine for is the programming languages of old. I cut my teeth on some fairly gnarly languages. Over those early years, I worked with various implementations of BASIC, C, Delphi, Perl, PHP, ASP, and Java but never felt truly comfortable with any of their designs or infrastructure. There was always something missing, some hiccup of design decisions that would bite me here and there (or often). In 2009, when Go was publicly announced, I gave it a shot without a lot of hope. I knew the pedigree of its designers but figured I was dealing with another com- plicated C alternative. Within a short period, I realized this was one of the cleanest and most enjoyable languages I’d ever worked with. It got out of my way. I got things done. I lobbied for using it for work and started building in Go almost immediately. Although it’s not the only tool in my toolbox these days, I still write Go every day. As amazing as it is, one underappreciated aspect of Go is how it jump-started zeal for creating new, modern languages that can use the power in the systems we have today and produce for the landscape of contemporary use cases. Since Go’s arrival, we’vexii
Page 12
PREFACE xiiiseen Rust, Zig, Nim, Odin, Carbon, and others join the space, trying to solve the same problems in elegant ways. Although all of them have merits, Go still provides every- thing needed for simple, clean, garbage-collected compiled code. If you’re coming from another systems language, you’ll appreciate the built-in tooling. The onboard package manager is simple and gets out of your way. The testing suite gives you everything you need to add tests and build into your pipeline. The code formatter go fmt means no more arguments about style or linting. If you’re coming in with some Go experience, I hope this book provides some tips and direction about getting things done with the language. We’ll look at a lot of disso- nant topics and hope to cover a lot of ground with small but demonstrative examples. More than anything, I hope you get some inspiration from this book to keep coding with Go and immersing in the Go community. —NATHAN KOZYRA
Page 13
acknowledgments Writing a book (or even a book revision) takes a lot of blood, sweat, and tears, and a lot of people must come together to take the book from concept to print. I’d like to thank the people who helped this book come to fruition. Time sacrifices from the author can affect a lot of people both related and unre- lated, and I first want to thank my family and close friends, who worked around my obligations that took days and weekends away. Without their understanding, the book could never have been completed. Writing and revisions take more time than most authors anticipate, and I appreciate all the buffers those close to me provided to help me get to the finish line. I received a similar cushion from my employer and co-workers, who knew the time commitment and gave me all the space and support I needed. In writing this book, I got immeasurable support from the Manning team. In par- ticular, I’d like to call out and thank my development editor, Jeffrey Wajsberg. Jeffrey was phenomenal along the way in calling out improvements in writing style, clarity, structure, and in some cases basic grammar. The scheduling, pacing, and writing would have been impossible without that guidance. The supporting team members at Manning never missed a beat, keeping this project moving along at a brisk but con- trolled pace. To the book reviewers, I appreciate your attention to detail, finding small things at a technical level that might have slipped through the cracks otherwise. From small suggestions to idiomatic Go language improvements, the book greatly improved from their feedback. To all the reviewers: Adir Shemesh, Andreas Schroepfer, Anuj More,xiv
Page 14
ACKNOWLEDGMENTS xvBorko Djurkovic, Christopher Neeb, Clifford Thurber, Dan Sheikh, Diego Stamigni, Ernest Addae, Giuseppe Maxia, Jasmeet Singh, Jason Content, Jerome Meyer, Jim Amrhein, Joel Holmes, Jonathan Reeves, Keith Kim, Leonardo Taccari, Manzur, Michele Di Pede, Mihaela Barbu, Neeraj Shah, Nolan, Paul Snow, Pavel Anni, Peter Sellars, Ramanan N, Sachin Handiekar, Scott Ling, Sergio Britos Arevalo, Tom Howarth, Tony Holdroyd, and Zachary Manning, your suggestions helped make this book better. Last, I’d like to show some love to the Go team at Google. In my 30-plus years of development both as a profession and as a hobby, I’ve never found a language that lets me just get things done like this one. Go is a legitimately fun language, and when I move to other languages I’m reminded of the simplicity and attention to tight, read- able language design that’s key to Go’s core ethos. I hope the language keeps growing and you find working with Go as fun and as productive as I have. —NATHAN KOZYRA
Page 15
about this book Go in Practice, Second Edition, is intended to be a high-level approach to getting com- fortable with concepts above and beyond the basics of the language. Topics range from building concurrent systems with Go’s goroutine approach to building perfor- mant web applications, all along learning about the tools that enable production-qual- ity code. You’ll learn about dealing with networking, file access, concurrency patterns, and using native communication protocols like TCP/REST, gRPC, and UDP. The book also emphasizes testing and error handling to empower the reader to build solid systems that hold up to real-world challenges. Who should read this book? This book is intended for intermediate Go developers and advanced developers in adjacent languages like Java, C/C++, C#, and Rust, among others. But developers from other languages just hoping to get their feet wet with Go should be able to follow along without too much trouble. Go is simple by design and has a low barrier to entry, which makes learning along the way more than manageable. How this book is organized: A road map This book has 13 chapters divided into four thematic parts. The first part is an overview of the general structure, functionality, and tooling included in the Go suite.xvi
Page 16
ABOUT THIS BOOK xvii Chapter 1 makes sure the reader gets up and Going with the language. We com- pare Go to other comparable languages (both legacy and new), show how to lay out and build Go applications, and deal with dependencies. Chapter 2 looks at building command-line applications using flags, configura- tion, and environment variables. From the basics of command-line interface design, we’ll dig into starting and gracefully stopping a web server. Chapter 3 digs into the core data structures in Go: structs and interfaces. We look at how to design custom abstract data types and use interfaces to guaran- tee compatibility with functions and methods. We also dig into the much-dis- cussed, finally implemented generics features of Go. The next part looks at the types of development fundamentals and tooling you’ll need to ensure that your applications are ready for real-world users by focusing on error handling, testing, and performance improvements with concurrency. Chapter 4 discusses error handling approaches and dealing with panics. We’ll cover various approaches to bubbling and wrapping errors, and compare pan- ics to other methods of exiting a program. Chapter 5 explores concurrency, one of Go’s primary selling points. We’ll look at the model itself, demonstrating goroutines and channels for communication between concurrent goroutines. Chapter 6 jumps into Go’s powerful testing functionality, showing how to benchmark and test your code. You use test tables to build easily readable and augmentable groups of tests and test suites to keep your code functioning through potential edge cases and regressions. Chapter 7 walks you through the basics of working with file systems and net- working in Go. You’ll learn how to access, read, and write files and glean insights from operating system-level file stats. We’ll also build basic networking at a low level with both TCP and UDP. The third part of this book puts the tools from the first two parts into practice in build- ing a web service both as a server and as a client. You’ll deal with handling requests and with delivering them as a consumer of other web services. Chapter 8 builds on the previous lessons and applies them to design a working HTTP server. Go has a robust standard library for building servers, and we’ll build on that to create a working web server while demonstrating routing and dealing with HTTP requests and responses, including cookies and authentication. Chapter 9 extends basic web servers to something approaching a real-world web app. We’ll look at Go’s templating system to return responses using abstract templates for the web, email, and other text-based purposes. Chapter 10 deals with advanced topics related to web applications. You’ll learn about creating standalone or adjacent static file servers, embedding data directly in your compiled binary, and working with POST data and file uploads.
Page 17
ABOUT THIS BOOKxviii Chapter 11 looks at working with external services, wherein we work in a network- ing space as a client rather than exclusively as a server. You’ll learn about design- ing APIs and dealing with external ones and their protocols. We’ll also look at an alternative to REST, gRPC, and how it can be used to reinforce your code. The final part looks at some more fine-grained and advanced use cases for Go as they relate to our previous chapters. Chapter 12 focuses on running and building your apps for cloud deployment. We first dig into using Go to help orchestrate your cloud service(s), dealing with networking and discoverability concerns that go along with such deploy- ments, including monitoring. In addition, we look at alternatives for cloud com- munication like gRPC both as a server and as a consumer of APIs. Chapter 13 looks at some advanced and niche parts of the Go ecosystem. Going deeper on runtime reflection and the type system will help you build better libraries and more generalized code. We’ll look at interoperability with C and more granular control of Go’s garbage collection. About the code As you read the book, you’ll encounter a bevy of code examples. Many of those are shown in their entirety and can be compiled without accompaniment. The fact that full source code could be included demonstrates the brevity and simplicity of Go’s design! You’ll also find code in text designated in this fixed-width font and style to demon- strate snippets that are referenced in preceding code or can be changed to affect the behavior of that code. Often, these blocks of code draw attention to code that war- rants additional detail or explanation. You can get executable snippets of code from the liveBook (online) version of this book at https://livebook.manning.com/book/go-in-practice-second-edition. You can find the complete and most up-to-date version of the code as a Git repository at https:// github.com/nkozyra/go-in-practice and on the Manning website at www.manning.com. liveBook discussion forum Purchase of Go in Practice, Second Edition, includes free access to liveBook—Manning’s online reading platform. Using liveBook’s exclusive discussion features, you can attach comments to the book globally or to specific sections or paragraphs. It’s a snap to make notes for yourself, ask and answer technical questions, and receive help from the authors and other users. To access the forum, go to https://livebook.manning.com/ book/go-in-practice-second-edition/discussion. You can also learn more about Man- ning’s forums and the rules of conduct at https://livebook.manning.com/discussion. Manning’s commitment to our readers is to provide a venue where meaningful dialogue between individual readers and between readers and authors can take place. It is not a commitment to any specific amount of participation on the part of the authors, whose contributions to the forum remain voluntary (and unpaid). We suggest
Page 18
ABOUT THIS BOOK xixyou try asking the authors some challenging questions lest their interest stray! The forum and the archives of previous discussions will be accessible on the publisher’s website as long as the book is in print. Other online resources Beyond this book and similar books, there are a few great resources for continued learning in Go. Reddit’s Go subreddit at https://www.reddit.com/r/golang is a great place for both new and experienced Go developers. Stack Overflow remains a high-quality source to submit, assist, and review common questions and challenges using Go. See https://stackoverflow.com/ questions/tagged/golang. Referenced heavily in this book, Go’s internal documentation is comprehensive and easy to follow. The standard library reference provides quick access to the core platform’s functionality. See https://pkg.go.dev/std. The authors highly recommend the Golang Weekly newsletter, which can sur- face cool projects written with Go and brings light to new and proposed changes to the language. Subscribe to it at https://golangweekly.com.
Page 19
about the authors NATHAN KOZYRA is a full-stack developer who has been building web and mobile applications for more than 30 years. An early adopter of the Go language, he’s been actively developing with it since 2009. In addition to doing web/mobile work, he has an MS in Computer Science with a focus on machine learning and has been building machine learning solutions for more than a decade. In addition to Go, he works heavily with TypeScript and Rust and enjoys experimenting with new systems languages emerging in the space, like Odin and Zig. MATT BUTCHER is an architect at Deis, where contributing to open source projects is his day job. He has written several books and dozens of articles. Matt holds a PhD in philosophy and teaches in the Computer Science department at Loyola Univer- sity Chicago. Matt is passionate about building strong teams and developing elegant solutions to complex problems.xx
Page 20
ABOUT THE AUTHORS xxiMATT FARINA is a Principal Engineer in the Advanced Technol- ogy Group at Hewlett Packard Enterprise. He is an author, speaker, and regular contributor to open source software who has been developing software for over a quarter century. He likes to solve problems for regular people by creating solutions using both the latest technology and the mundane that can be easily overlooked.
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

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List