36,59 €
Tackle the trickiest of problems in Go programming with this practical guide
Key Features
Book Description
Go (or Golang) is a statically typed programming language developed at Google. Known for its vast standard library, it also provides features such as garbage collection, type safety, dynamic-typing capabilities, and additional built-in types. This book will serve as a reference while implementing Go features to build your own applications.
This Go cookbook helps you put into practice the advanced concepts and libraries that Golang offers. The recipes in the book follow best practices such as documentation, testing, and vendoring with Go modules, as well as performing clean abstractions using interfaces. You'll learn how code works and the common pitfalls to watch out for. The book covers basic type and error handling, and then moves on to explore applications, such as websites, command-line tools, and filesystems, that interact with users. You'll even get to grips with parallelism, distributed systems, and performance tuning.
By the end of the book, you'll be able to use open source code and concepts in Go programming to build enterprise-class applications without any hassle.
What you will learn
Who this book is for
If you're a web developer, programmer, or enterprise developer looking for quick solutions to common and not-so-common problems in Go programming, this book is for you. Basic knowledge of the Go language is assumed.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 369
Veröffentlichungsjahr: 2019
Copyright © 2019 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor:Amey VarangaonkarAcquisition Editor:Shahnish KhanContent Development Editor:Rohit Kumar SinghTechnical Editor:Romy DiasCopy Editor: Safis EditingProject Coordinator:Vaidehi SawantProofreader: Safis EditingIndexer: Tejal Daruwale SoniProduction Designer: Aparna BhagatGraphic Coordinator: Alishon Mendonsa
First published: June 2017 Second edition: July 2019
Production reference: 1190719
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78980-098-2
www.packtpub.com
Packt.com
Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Fully searchable for easy access to vital information
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Aaron Torres received his master's degree in computer science from the New Mexico Institute of Mining and Technology. He has worked on distributed systems in high-performance computing and in large-scale web and microservices applications. He currently leads a team of Go developers that refines and focuses on Go best practices with an emphasis on continuous delivery and automated testing.
Aaron has published a number of papers and has several patents in the area of storage and I/O. He is passionate about sharing his knowledge and ideas with others. He is also a huge fan of the Go language and open source for backend systems and development.
Eduard Bondarenko is a software developer living in Kyiv, Ukraine. He started programming using BASIC on ZXSpectrum a long time ago. Later, he worked in the web development domain. He has used Ruby on Rails for over 8 years. Having used Ruby for a long time, he discovered Clojure in early 2009, and liked the simplicity of language. Besides Ruby and Clojure, he is interested in Go and ReasonML development.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Go Programming Cookbook Second Edition
Dedication
About Packt
Why subscribe?
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Code in Action
Conventions used
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Get in touch
Reviews
I/O and Filesystems
Technical requirements
Using the common I/O interfaces
How to do it...
How it works...
Using the bytes and strings packages
How to do it...
How it works...
Working with directories and files
How to do it...
How it works...
Working with the CSV format
How to do it...
How it works...
Working with temporary files
How to do it...
How it works...
Working with text/template and html/template
How to do it...
How it works...
Command-Line Tools
Technical requirements
Using command-line flags
How to do it...
How it works...
Using command-line arguments
How to do it...
How it works...
Reading and setting environment variables
How to do it...
How it works...
Configuration using TOML, YAML, and JSON
How to do it...
How it works...
Working with Unix pipes
How to do it...
How it works...
Catching and handling signals
How to do it...
How it works...
An ANSI coloring application
How to do it...
How it works...
Data Conversion and Composition
Technical requirements
Converting data types and interface casting
How to do it...
How it works...
Working with numeric data types using math and math/big
How to do it...
How it works...
Currency conversions and float64 considerations
How to do it...
How it works...
Using pointers and SQL NullTypes for encoding and decoding
How to do it...
How it works...
Encoding and decoding Go data
How to do it...
How it works...
Structure tags and basic reflection in Go
How to do it...
How it works...
Implementing collections via closures
How to do it...
How it works...
Error Handling in Go
Technical requirements
Handling errors and the Error interface
How to do it...
How it works...
Using the pkg/errors package and wrapping errors
How to do it...
How it works...
Using the log package and understanding when to log errors
How to do it...
How it works...
Structured logging with the apex and logrus packages
How to do it...
How it works...
Logging with the context package
How to do it...
How it works...
Using package-level global variables
How to do it...
How it works...
Catching panics for long-running processes
How to do it...
How it works...
Network Programming
Technical requirements
Writing a TCP/IP echo server and client
How to do it...
How it works...
Writing a UDP server and client
How to do it...
How it works...
Working with domain name resolution
How to do it...
How it works...
Working with WebSockets
How to do it...
How it works...
Working with net/rpc for calling remote methods
How to do it...
How it works...
Using net/mail for parsing emails
How to do it...
How it works...
All about Databases and Storage
Using the database/sql package with MySQL
Getting ready
How to do it...
How it works...
Executing a database transaction interface
Getting ready
How to do it...
How it works...
Connection pooling, rate limiting, and timeouts for SQL
Getting ready
How to do it...
How it works...
Working with Redis
Getting ready
How to do it...
How it works...
Using NoSQL with MongoDB
Getting ready
How to do it...
How it works...
Creating storage interfaces for data portability
Getting ready
How to do it...
How it works...
Web Clients and APIs
Technical requirements
Initializing, storing, and passing http.Client structures
How to do it...
How it works...
Writing a client for a REST API
How to do it...
How it works...
Executing parallel and async client requests
How to do it...
How it works...
Making use of OAuth2 clients
Getting ready
How to do it...
How it works...
Implementing an OAuth2 token storage interface
Getting ready
How to do it...
How it works...
Wrapping a client in added functionality and function composition
How to do it...
How it works...
Understanding GRPC clients
Getting ready
How to do it...
How it works...
Using twitchtv/twirp for RPC
Getting ready
How to do it...
How it works...
Microservices for Applications in Go
Technical requirements
Working with web handlers, requests, and ResponseWriter instances
How to do it...
How it works...
Using structures and closures for stateful handlers
How to do it...
How it works...
Validating input for Go structures and user inputs
How to do it...
How it works...
Rendering and content negotiation
How to do it...
How it works...
Implementing and using middleware
How to do it...
How it works...
Building a reverse proxy application
How to do it...
How it works...
Exporting GRPC as a JSON API
Getting ready
How to do it...
How it works...
Testing Go Code
Technical requirements
Mocking using the standard library
How to do it...
How it works...
Using the Mockgen package to mock interfaces
Getting ready
How to do it...
How it works...
Using table-driven tests to improve coverage
How to do it...
How it works...
Using third-party testing tools
Getting ready
How to do it...
How it works...
Behavior testing using Go
Getting ready
How to do it...
How it works...
Parallelism and Concurrency
Technical requirements
Using channels and the select statement
How to do it...
How it works...
Performing async operations with sync.WaitGroup
How to do it...
How it works...
Using atomic operations and mutex
How to do it...
How it works...
Using the context package
How to do it...
How it works...
Executing state management for channels
How to do it...
How it works...
Using the worker pool design pattern
How to do it...
How it works...
Using workers to create pipelines
How to do it...
How it works...
Distributed Systems
Technical requirements
Using service discovery with Consul
How to do it...
How it works...
Implementing basic consensus using Raft
How to do it...
How it works...
Using containerization with Docker
Getting ready
How to do it...
How it works...
Orchestration and deployment strategies
How to do it...
How it works...
Monitoring applications
How to do it...
How it works...
Collecting metrics
Getting ready
How to do it...
How it works...
Reactive Programming and Data Streams
Technical requirements
Using Goflow for data flow programming
How to do it...
How it works...
Using Kafka with Sarama
Getting ready
How to do it...
How it works...
Using async producers with Kafka
Getting ready
How to do it...
How it works...
Connecting Kafka to Goflow
Getting ready
How to do it...
How it works...
Writing a GraphQL server in Go
How to do it...
How it works...
Serverless Programming
Go programming on Lambda with Apex
Getting ready
How to do it...
How it works...
Apex serverless logging and metrics
Getting ready
How to do it...
How it works...
Google App Engine with Go
Getting ready
How to do it...
How it works...
Working with Firebase using firebase.google.com/go
Getting ready
How to do it...
How it works...
Performance Improvements, Tips, and Tricks
Technical requirements
Using the pprof tool
How to do it...
How it works...
Benchmarking and finding bottlenecks
How to do it...
How it works...
Memory allocation and heap management
How to do it...
How it works...
Using fasthttprouter and fasthttp
How to do it...
How it works...
Other Books You May Enjoy
Leave a review - let other readers know what you think
Thank you for choosing this book! I hope it will be a handy reference for developers to quickly look up Go development patterns. It is meant to be a companion to other resources and a reference that will hopefully be useful long after reading it once. Each recipe in this book includes working, simple, and tested code that can be used as a reference or foundation for your own applications. The book covers a range of content from basic to advanced topics.
This book is aimed for web developers, programmers, and enterprise developers. Basic knowledge of the Go language is assumed. Experience with backend application development is not necessary, but may help understand the motivation behind some of the recipes.
This book serves as a good reference for Go developers who are already proficient but need a quick reminder, example, or reference. With the open source repository, it should be possible to share these examples quickly with a team as well. If you are looking for quick solutions to common and not-so-common problems in Go programming, this book is for you.
Chapter 1, I/O and Filesystems, covers common Go I/O interfaces and explores working with filesystems. This includes temporary files, templates, and CSV files.
Chapter 2, Command-Line Tools, looks at taking in user input via the command line and explores processing common datatypes such as TOML, YAML, and JSON.
Chapter 3, Data Conversion and Composition, demonstrates methods for casting and converting between Go interfaces and data types. It also showcases encoding strategies and some functional design patterns for Go.
Chapter 4, Error Handling in Go, showcases strategies to handle errors in Go. It explores how to pass errors, handle them, and log them.
Chapter 5, Network Programming, demonstrates usage of various networking primitives such as UDP and TCP/IP. It also explores Domain Name System (DNS), working with raw email messages, and basic Remote Procedure Call (RPC).
Chapter 6, All about Databases and Storage, deals with various storage libraries for accessing data storage systems such as MySQL. It also demonstrates the use of interfaces to decouple your library from your application logic.
Chapter 7, Web Clients and APIs, implements Go HTTP client interfaces, REST clients, OAuth2 clients, decorating and extending clients, and gRPC.
Chapter 8, Microservices for Applications in Go, explores web handlers, passing in a state to a handler, validation of user input, and middleware.
Chapter 9, Testing Go Code, focuses on mocking, test coverage, fuzzing, behavior testing, and helpful testing tools.
Chapter 10, Parallelism and Concurrency, provides a reference for channels and async operations, atomic values, Go context objects, and channel state management.
Chapter 11, Distributed Systems, implements service discovery, Docker containerization, metrics and monitoring, and orchestration. It mostly deals with deployment and productionization of Go applications.
Chapter 12, Reactive Programming and Data Streams, explores reactive and dataflow applications, Kafka and distributed message queues, and GraphQL servers.
Chapter 13, Serverless Programming, deals with deploying Go applications without maintaining a server. This includes using Google App Engine, Firebase, Lambda, and logging in a serverless environment.
Chapter 14, Performance Improvements, Tips, and Tricks, deals with benchmarking, identifying bottlenecks, optimizing, and improving the HTTP performance for Go applications.
To use this book, you'll need the following:
A Unix programming environment.
The latest version of the Go 1.x series.
An internet connection.
Permission to install additional packages as described in each chapter.
Prerequisites and other installation requirements for each recipe are mentioned in the
Technical requirements
section of the respective chapters.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
Visit the following link to check out videos of the code being run: http://bit.ly/2J2uqQ3
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The bytes library provides a number of convenient functions when working with data."
A block of code is set as follows:
b, err := ioutil.ReadAll(r) if err != nil { return "", err } return string(b), nil }
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
package bytestrings import ( "
bytes
" "
io
" "
io/ioutil
" )
Any command-line input or output is written as follows:
$ go mod init github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/Chapter01/interfaces
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."
In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).
To give clear instructions on how to complete a recipe, use these sections as follows:
This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
Go provides excellent support for both basic and complex I/O. The recipes in this chapter will explore common Go interfaces that are used to deal with I/O and show you how to make use of them. The Go standard library frequently uses these interfaces, and they will be used by recipes throughout the book.
You'll learn how to work with data in memory and in the form of streams. You'll see examples of working with files, directories, and the CSV format. The temporary files recipe looks at a mechanism to work with files without the overhead of dealing with name collision and more. Lastly, we'll explore Go standard templates for both plain text and HTML.
These recipes should lay the foundation for the use of interfaces to represent and modify data, and should help you think about data in an abstract and flexible way.
In this chapter, the following recipes will be covered:
Using the common I/O interfaces
Using the bytes and strings packages
Working with directories and files
Working with the CSV format
Working with temporary files
Working with text/template and html/template
In order to proceed with all the recipes in this chapter, configure your environment according to these steps:
Download and install Go 1.12.6 or greater on your operating system at
https://golang.org/doc/install
.
Open a Terminal or console application and create and navigate to a project directory, such as
~/projects/go-programming-cookbook
.
All code will be run and modified from this directory.
Clone the latest code into
~/projects/go-programming-cookbook-original
, as shown in the following code. It is recommended that you work from that directory rather than typing the examples manually:
$ git clone [email protected]:PacktPublishing/Go-Programming-Cookbook-Second-Edition.git go-programming-cookbook-original
The Go language provides a number of I/O interfaces that are used throughout the standard library. It is best practice to make use of these interfaces wherever possible rather than passing structures or other types directly. Two powerful interfaces we will explore in this recipe are the io.Reader and io.Writer interfaces. These interfaces are used throughout the standard library, and understanding how to use them will make you a better Go developer.
The Reader and Writer interfaces look like this:
type Reader interface { Read(p []byte) (n int, err error)}type Writer interface { Write(p []byte) (n int, err error)}
Go also makes it easy to combine interfaces. For example, take a look at the following code:
type Seeker interface { Seek(offset int64, whence int) (int64, error)}type ReadSeeker interface { Reader Seeker}
This recipe will also explore an io function called Pipe(), as shown in the following code:
func Pipe() (*PipeReader, *PipeWriter)
The remainder of this book will make use of these interfaces.
The Copy() function copies bytes between interfaces and treats that data like a stream. Thinking of data as streams has a lot of practical uses, especially when working with network traffic or filesystems. The Copy() function also creates a MultiWriter interface that combines two writer streams and writes to them twice using ReadSeeker. If a Reader interface was used instead, rather than seeing exampleexample, you would only see example despite copying to the MultiWriter interface twice. You can also use a buffered write if your stream is not fitted into the memory.
The PipeReader and PipeWriter structures implement the io.Reader and io.Writer interfaces. They're connected, creating an in-memory pipe. The primary purpose of a pipe is to read from a stream while simultaneously writing from the same stream to a different source. In essence, it combines the two streams into a pipe.
Go interfaces are a clean abstraction to wrap data that performs common operations. This is made apparent when doing I/O operations, and so the io package is a great resource for learning about interface composition. The pipe package is often underused, but provides great flexibility with thread safety when linking input and output streams.
The bytes and strings packages have a number of useful helpers to work with and convert the data from string to byte types, and vice versa. They allow the creation of buffers that work with a number of common I/O interfaces.
The bytes library provides a number of convenience functions when working with data. A buffer, for example, is far more flexible than an array of bytes when working with stream-processing libraries or methods. Once you've created a buffer, it can be used to satisfy an io.Reader interface so that you can take advantage of ioutil functions to manipulate the data. For streaming applications, you'd probably want to use a buffer and a scanner. The bufio package comes in handy for these cases. Sometimes, using an array or slice is more appropriate for smaller datasets or when you have a lot of memory on your machine.
Go provides a lot of flexibility in converting data between interfaces when using these basic types—it's relatively simple to convert between strings and bytes. When working with strings, thestringspackage provides a number of convenience functions to work with, search, and manipulate strings. In some cases, a good regular expression may be appropriate, but most of the time, thestringsandstrconvpackages are sufficient. Thestringspackage allows you to make a string look like a title, split it into an array, or trim whitespace. It also provides aReaderinterface of its own that can be used instead of thebytespackage reader type.
Working with directories and files can be difficult when you switch between platforms (Windows and Linux, for example). Go provides cross-platform support to work with files and directories in the os and ioutils packages. We've already seen examples of ioutils, but now we'll explore how to use them in another way!
If you're familiar with files in Unix, the Go os library should feel very familiar. You can perform basically all common operations—Stat a file to collect attributes, collect a file with different permissions, and create and modify directories and files. In this recipe, we performed a number of manipulations to directories and files and then cleaned up after ourselves.
Working with file objects is very similar to working with in-memory streams. Files also provide a number of convenience functions directly, such as Chown, Stat, and Truncate. The easiest way to get comfortable with files is to make use of them. In all the previous recipes, we have to be careful to clean up after our programs.
Working with files is a very common operation when building backend applications. Files can be used for configuration, secret keys, as temporary storage, and more. Go wraps OS system calls using the os package and allows the same functions to operate regardless of whether you're using Windows or Unix.
Once your file is opened and stored in a File structure, it can easily be passed into a number of interfaces (we discussed these interfaces earlier). All the earlier examples can use os.File structures directly instead of buffers and in-memory data streams in order to operate on data stored on the disk . This may be useful for certain techniques, such as writing all logs to stderr and the file at the same time with a single write call.
CSV is a common format that is used to manipulate data. It's common, for example, to import or export a CSV file into Excel. The Go CSV package operates on data interfaces, and as a result, it's easy to write data to a buffer, stdout, a file, or a socket. The examples in this section will show some common ways to get data into and out of the CSV format.
