Go Cookbook - Aaron Torres - E-Book

Go Cookbook E-Book

Aaron Torres

0,0
41,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Bridge the gap between basic understanding of Go and use of its advanced features

About This Book

  • Discover a number of recipes and approaches to develop modern back-end applications
  • Put to use the best practices to combine the recipes for sophisticated parallel tools
  • This book is based on Go 1.8, which is the latest version

Who This Book Is For

This book is for web developers, programmers, and enterprise developers. Basic knowledge of the Go language is assumed. Experience with back-end application development is not necessary, but may help understand the motivation behind some of the recipes.

What You Will Learn

  • Test your application using advanced testing methodologies
  • Develop an awareness of application structures, interface design, and tooling
  • Create strategies for third-party packages, dependencies, and vendoring
  • Get to know tricks on treating data such as collections
  • Handle errors and cleanly pass them along to calling functions
  • Wrap dependencies in interfaces for ease of portability and testing
  • Explore reactive programming design patterns in Go

In Detail

Go (a.k.a. Golang) is a statically-typed programming language first developed at Google. It is derived from C with additional features such as garbage collection, type safety, dynamic-typing capabilities, additional built-in types, and a large standard library.

This book takes off where basic tutorials on the language leave off. You can immediately put into practice some of the more advanced concepts and libraries offered by the language while avoiding some of the common mistakes for new Go developers.

The book covers basic type and error handling. It explores applications that interact with users, such as websites, command-line tools, or via the file system. It demonstrates how to handle advanced topics such as parallelism, distributed systems, and performance tuning. Lastly, it finishes with reactive and serverless programming in Go.

Style and approach

This guide is a handy reference for developers to quickly look up Go development patterns. It is a companion to other resources and a reference that will be useful long after reading it through the first time. Each recipe includes working, simple, and tested code that can be used as a reference or foundation for your own applications.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 336

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Go Cookbook

 

 

 

 

 

 

 

 

Build modular, readable, and testable applications in Go

 

 

 

 

 

 

 

 

 

 

Aaron Torres

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

< html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

Go Cookbook

Copyright © 2017 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

 

First published: June 2017

 

Production reference: 1240617

 

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78328-683-6

www.packtpub.com

Credits

Author

Aaron Torres

Copy Editor

Pranjali Chury

Reviewer

Julien Da Silva

Project Coordinator

Vaidehi Sawant

Commissioning Editor

Kunal Parikh

Proofreader

Safis Editing

Acquisition Editor

Karan Sadawana

Indexer

Tejal Daruwale Soni

Content Development Editor

Rohit Kumar Singh

Graphics

Jason Monteiro

Technical Editor

Vivek Pala

Production Coordinator

Nilesh Mohite

About the Author

Aaron Torres received his master's of science degree in computer science from 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.

About the Reviewer

Julien Da Silva is a software engineer and architect specializing in scalable, distributed systems. Previously at Hailo, he was a part of the team that built its Golang platform, which is widely recognized as one of the early successful implementations of microservices. Hailo was later acquired by MyTaxi in 2016. He is currently working as a core architect at LastMileLink, part of CitySprint group, UK leader in same day courier services.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

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.PacktPub.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.PacktPub.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.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/Go-Cookbook-Aaron-Torres-ebook/dp/B01MS2MOFP/ref=sr_1_16?ie=UTF8&qid=1497940919&sr=8-16&keywords=go+cookbook.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Sections

Getting ready

How to do it…

How it works…

There's more…

See also

Conventions

Reader feedback

Customer support

Downloading the example code

Errata

Piracy

Questions

I/O and File Systems

Introduction

Using the common I/O interfaces

Getting ready

How to do it...

How it works...

Using the bytes and strings packages

Getting ready

How to do it...

How it works...

Working with directories and files

Getting ready

How to do it...

How it works...

Working with the CSV format

Getting ready

How to do it...

How it works...

Working with temporary files

Getting ready

How to do it...

How it works...

Working with text/template and HTML/templates

Getting ready

How to do it...

How it works...

Command-Line Tools

Introduction

Using command-line flags

Getting ready

How to do it...

How it works...

Using command-line arguments

Getting ready

How to do it...

How it works...

Reading and setting environment variables

Getting ready

How to do it...

How it works...

Configuration using TOML, YAML, and JSON

Getting ready

How to do it...

How it works...

Working with Unix pipes

Getting ready

How to do it...

How it works...

Catching and handling signals

Getting ready

How to do it...

How it works...

An ANSI coloring application

Getting ready

How to do it...

How it works...

Data Conversion and Composition

Introduction

Converting data types and interface casting

Getting ready

How to do it...

How it works...

Working with numeric data types using math and math/big

Getting ready

How to do it...

How it works...

Currency conversions and float64 considerations

Getting ready

How to do it...

How it works...

Using pointers and SQL NullTypes for encoding and decoding

Getting ready

How to do it...

How it works...

Encoding and decoding Go data

Getting ready

How to do it...

How it works...

Struct tags and basic reflection in Go

Getting ready

How to do it...

How it works...

Implementing collections via closures

Getting ready

How to do it...

How it works...

Error Handling in Go

Introduction

Handling errors and the Error interface

Getting ready

How to do it...

How it works...

Using the pkg/errors package and wrapping errors

Getting ready

How to do it...

How it works...

Using the log package and understanding when to log errors

Getting ready

How to do it...

How it works...

Structured logging with the apex and logrus packages

Getting ready

How to do it...

How it works...

Logging with the context package

Getting ready

How to do it...

How it works...

Using package-level global variables

Getting ready

How to do it...

How it works...

Catching panics for long running processes

Getting ready

How to do it...

How it works...

All about Databases and Storage

Introduction

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 and mgo

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

Introduction

Initializing, storing, and passing http.Client structs

Getting ready

How to do it...

How it works...

Writing a client for a REST API

Getting ready

How to do it...

How it works...

Executing parallel and async client requests

Getting ready

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

Getting ready

How to do it...

How it works...

Understanding GRPC clients

Getting ready

How to do it...

How it works...

Microservices for Applications in Go

Introduction

Working with web handlers, requests, and ResponseWriters

Getting ready

How to do it...

How it works...

Using structs and closures for stateful handlers

Getting ready

How to do it...

How it works...

Validating input for Go structs and user inputs

Getting ready

How to do it...

How it works...

Rendering and content negotiation

Getting ready

How to do it...

How it works...

Implementing and using middleware

Getting ready

How to do it...

How it works...

Building a reverse proxy application

Getting ready

How to do it...

How it works...

Exporting GRPC as a JSON API

Getting ready

How to do it...

How it works...

Testing

Introduction

Mocking using the standard library

Getting ready

How to do it...

How it works...

Using the Mockgen package

Getting ready

How to do it...

How it works...

Using table-driven tests to improve coverage

Getting ready

How to do it...

How it works...

Using third-party testing tools

Getting ready

How to do it...

How it works...

Practical fuzzing

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

Introduction

Using channels and the select statement

Getting ready

How to do it...

How it works...

Performing async operations with sync.WaitGroup

Getting ready

How to do it...

How it works...

Using atomic operations and mutex

Getting ready

How to do it...

How it works...

Using the context package

Getting ready

How to do it...

How it works...

Executing state management for channels

Getting ready

How to do it...

How it works...

Using the worker pool design pattern

Getting ready

How to do it...

How it works...

Using workers to create pipelines

Getting ready

How to do it...

How it works...

Distributed Systems

Introduction

Using service discovery with Consul

Getting ready

How to do it...

How it works...

Implementing basic consensus using Raft

Getting ready

How to do it...

How it works...

Using containerization with Docker

Getting ready

How to do it...

How it works...

Orchestration and deployment strategies

Getting ready

How to do it...

How it works...

Monitoring applications

Getting ready

How to do it...

How it works...

Collecting metrics

Getting ready

How to do it...

How it works...

Reactive Programming and Data Streams

Introduction

Goflow for dataflow programming

Getting ready

How to do it...

How it works...

Reactive programming with RxGo

Getting ready

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

Getting ready

How to do it...

How it works...

Serverless Programming

Introduction

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 zabawaba99/firego

Getting ready

How to do it...

How it works...

Performance Improvements, Tips, and Tricks

Introduction

Speeding up compilation and testing cycles

Getting ready

How to do it...

How it works...

Using the pprof tool

Getting ready

How to do it...

How it works...

Benchmarking and finding bottlenecks

Getting ready

How to do it...

How it works...

Memory allocation and heap management

Getting ready

How to do it...

How it works...

Vendoring and project layout

Getting ready

How to do it...

How it works...

Using fasthttprouter and fasthttp

Getting ready

How to do it...

How it works...

Preface

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.

What this book covers

Chapter 1, I/O and File Systems, 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 a 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, 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 6, Web Clients and APIs, implements Go HTTP client interfaces, REST clients, OAuth2 clients, decorating and extending clients, and GRPC.

Chapter 7, Microservices for Applications in Go, explores web handlers, passing in a state to a handler, validation of user input, and middleware.

Chapter 8, Testing, focuses on mocking, test coverage, fuzzing, behavior testing, and helpful testing tools.

Chapter 9, Parallelism and Concurrency, provides a reference for channels and async operations, atomic values, Go context objects, and channel state management.

Chapter 10, Distributed Systems, implements service discovery, Docker containerization, metrics and monitoring, and orchestration. It mostly deals with deployment and productionisation of Go applications.

Chapter 11, Reactive Programming and Data Streams, explores reactive and dataflow applications, Kafka and distributed message queues, and GraphQL servers.

Chapter 12, Serverless Programming, deals with deploying Go applications without maintaining a server. This includes using Google App Engine, Firebase, Lambda, and logging in these serverless environment.

Chapter 13, Performance Improvements, Tips, and Tricks, is the final chapter and deals with benchmarking, identifying bottlenecks, optimizing, and improving the HTTP performance for Go applications.

What you need for this book

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

Who this book is for

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.

Sections

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, we use these sections as follows:

Getting ready

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.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The Copy() function copies between interfaces and treats them like streams."

A block of code is set as follows:

package mainimport "github.com/agtorre/go-cookbook/chapter1/tempfiles"func main() { if err := tempfiles.WorkWithTemp(); err != nil { panic(err) }}

Any command-line input or output is written as follows:

$ go run main.go

/var/folders/kd/ygq5l_0d1xq1lzk_c7htft900000gn/T/tmp764135258/tmp588787953

New terms and important words are shown in bold.

Warnings or important notes appear in a box like this.
Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors .

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account. 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 at https://github.com/PacktPublishing/Go-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

I/O and File Systems

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/templates

Introduction

Go provides excellent support for both basic and complex I/O. The recipes in this chapter will explore common Go interfaces to deal with I/O and show how to make use of them. The Go standard library frequently uses these interfaces, and these interfaces 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 and directories and of working with the CSV format. The temporary files recipe discusses 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.

Using the common I/O interfaces

Go provides a number of I/O interfaces used throughout the standard library. It is a best practice to make use of these interfaces wherever possible rather than passing structs or other types directly. Two powerful interfaces we 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}

The recipe will also explore an io function called Pipe():

func Pipe() (*PipeReader, *PipeWriter)

The remainder of this book will make use of these interfaces.

Getting ready

Configure your environment according to these steps:

Download and install Go on your operating system at

https://golang.org/doc/install

and configure your

GOPATH

environment variable.

Open a terminal/console application, navigate to your

GOPATH/src

directory, and create a project directory such as

$GOPATH/src/github.com/yourusername/customrepo

.

All code will be run and modified from this directory.

Optionally, install the latest tested version of the code using the following command:

go get github.com/agtorre/go-cookbook/

How it works...

The Copy() function copies between interfaces and treats them like streams. 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 multi-writer that combines two writer streams and writes to them twice using ReadSeeker. If a Reader interface were used instead rather than seeing exampleexample, you would only see example despite copying to the MultiWriter interface twice. There's also an example of a buffered write that you might use if your stream is not fit into the memory.

The PipeReader and PipeWriter structs implement 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.

Using the bytes and strings packages

The bytes and string packages have a number of useful helpers to work with and convert between strings and byte types. They allow the creation of buffers that work with a number of common I/O interfaces.

Getting ready

Refer to the Getting ready section's steps in the Using the common I/O interfaces recipe.

How it works...

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 you can take advantage of ioutil functions to manipulate the data. For steaming 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 between interfaces with these basic types--it's relatively simple to convert between strings and bytes. When working with strings, the strings package 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, the strings and strconv packages are sufficient. The strings package allows you to make a string look like a title, split it into an array, or trim whitespace. It also provides a Reader interface of its own that can be used instead of the bytes package reader type.

Working with directories and files

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!

Getting ready

Refer to the Getting ready section's steps in theUsing the common I/O interfaces recipe.

How it works...

If you're familiar with files in Unix, the Go os library should feel very familiar. You can do basically all common operations--stat a file to collect attributes, collect a file with different permissions, and create and modify directories and files. We performed a number of manipulations to directories and files and then cleaned up after ourselves.

Working with file objects is very similar to 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.