Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Go Cookbook
Go Cookbook

Go Cookbook: Build modular, readable, and testable applications in Go

Arrow left icon
Profile Icon Torres
Arrow right icon
AU$47.99 AU$53.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (3 Ratings)
eBook Jun 2017 400 pages 1st Edition
eBook
AU$47.99 AU$53.99
Paperback
AU$67.99
Subscription
Free Trial
Arrow left icon
Profile Icon Torres
Arrow right icon
AU$47.99 AU$53.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (3 Ratings)
eBook Jun 2017 400 pages 1st Edition
eBook
AU$47.99 AU$53.99
Paperback
AU$67.99
Subscription
Free Trial
eBook
AU$47.99 AU$53.99
Paperback
AU$67.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Go Cookbook

Command-Line Tools

In this chapter, the following recipes will be covered:

  • Using command-line flags
  • Using command-line arguments
  • Reading and setting environment variables
  • Configuration using TOML, YAML, and JSON
  • Working with Unix pipes
  • Catching and handling signals
  • An ANSI coloring application

Introduction

Command-line applications are among the easiest ways to handle user input and output. This chapter will focus on command-line-based interactions, such as command-line arguments, configuration, and environment variables. It'll conclude with a library for coloring text output in Unix and Bash for Windows.

With the recipes in this chapter, you should be equipped to handle expected and unexpected user input. The signal recipe is an example of cases where users may send unexpected signals to your application, and the pipes recipe is a good alternative to taking user inputs compared to flags or command-line arguments.

The ANSI color recipe will hopefully provide some examples of cleaning up output to users. For example, in logging, being able to color text based on its purpose can sometimes make large blocks of text significantly more clear.

...

Using command-line flags

The flag package makes it simple to add command-line flag arguments to a Go application. It has a few shortcomings--you tend to duplicate a lot of code in order to add shorthand versions of flags, and they're ordered alphabetically from the help prompt. There are a number of third-party libraries that attempt to address these shortcomings, but this chapter will focus on the standard library version and not on those libraries.

Getting ready

Configure your environment according to these steps:

  1. Download and install Go on your operating system from https://golang.org/doc/install, and configure your GOPATH environment variable:
  2. Open a terminal/console application, and navigate to your GOPATH/src and...

Using command-line arguments

The flags from the previous recipe are a type of command-line argument. This chapter will expand on other uses for these arguments by constructing a command that supports nested subcommands. This will demonstrate Flagsets and also use positional arguments passed into your application.

Like the previous recipe, this one requires a main function to run. There are a number of third-party packages to deal with complex nested arguments and flags, but we'll investigate how to do that using only the standard library.

Getting ready

Refer to the Getting ready section's steps in the Using command-line flags recipe.

...

Reading and setting environment variables

Environment variables are another way to pass state into an application beyond reading data in from a file or passing it explicitly over the command line. This recipe will explore some very basic getting and setting of environment variables and then work with the highly useful third-party library https://github.com/kelseyhightower/envconfig.

We'll build an application that can read a config via JSON or through environment variables. The next recipe will further explore alternative formats, including TOML and YAML.

Getting ready

Configure your environment according to these steps:

  1. Refer to the Getting ready section's steps in the Using command-line flags recipe.
  2. Run the go...

Configuration using TOML, YAML, and JSON

There are many configuration formats that Go, with the use of third-party libraries, has support for. Three of the most popular data formats are TOML, YAML, and JSON. Go can support JSON out of the box, and the others have clues on how to marshal/unmarshal or encode/decode data for these formats. The formats have many benefits beyond configuration, but this chapter will largely focus on converting a Go struct in the form of a configuration struct. This recipe will explore basic input and output using these formats.

These formats also provide an interface by which Go and applications written in other languages can share the same configuration. There are also a number of tools that deal with these formats and simplify working with them.

Getting...

Working with Unix pipes

Unix pipes are useful when passing the output of one program to the input of another. For example, take a look at this:

$ echo "test case" | wc -l
1

In a Go application, the left-hand side of the pipe can be read in using os.Stdin and acts like a file descriptor. To demonstrate this, this recipe will take an input on the left-hand side of a pipe and return a list of words and their number of occurrences. These words will be tokenized on white space.

Getting ready

Refer to the Getting ready section's steps in the Using command-line flags recipe.

How to do it...

...

Catching and handling signals

Signals are a useful way for the user or the OS to kill your running application. Sometimes, it makes sense to handle these signals in a more graceful way than the default behavior. Go provides a mechanism to catch and handle signals. In this recipe, we'll explore the handling of signals through the use of a signal handling the Go routine.

Getting ready

Refer to the Getting ready section's steps in the Using command-line flags recipe.

How to do it...

These steps cover writing and running your application:

  1. From your terminal/console...

An ANSI coloring application

Coloring an ANSI terminal application is handled by a variety of code before and after a section of text you want colored. This chapter will explore a basic coloring mechanism to color text red or plain. For a complete application, take a look at https://github.com/agtorre/gocolorize, which supports many more colors and text types and also implements the fmt.Formatter interface for ease of printing.

Getting ready

Refer to the Getting ready section's steps in the Using command-line flags recipe.

How to do it...

These steps cover writing...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • 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

Description

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.

Who is this book 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

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 28, 2017
Length: 400 pages
Edition : 1st
Language : English
ISBN-13 : 9781783286843
Vendor :
Google
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jun 28, 2017
Length: 400 pages
Edition : 1st
Language : English
ISBN-13 : 9781783286843
Vendor :
Google
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Can$ 273.97
Go Cookbook
AU$67.99
Building Microservices with Go
AU$67.99
Go: Design Patterns for Real-World Projects
AU$137.99
Total Can$ 273.97 Stars icon

Table of Contents

13 Chapters
I/O and File Systems Chevron down icon Chevron up icon
Command-Line Tools Chevron down icon Chevron up icon
Data Conversion and Composition Chevron down icon Chevron up icon
Error Handling in Go Chevron down icon Chevron up icon
All about Databases and Storage Chevron down icon Chevron up icon
Web Clients and APIs Chevron down icon Chevron up icon
Microservices for Applications in Go Chevron down icon Chevron up icon
Testing Chevron down icon Chevron up icon
Parallelism and Concurrency Chevron down icon Chevron up icon
Distributed Systems Chevron down icon Chevron up icon
Reactive Programming and Data Streams Chevron down icon Chevron up icon
Serverless Programming Chevron down icon Chevron up icon
Performance Improvements, Tips, and Tricks Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(3 Ratings)
5 star 66.7%
4 star 0%
3 star 33.3%
2 star 0%
1 star 0%
Ben H. May 11, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I thought the book did a great job showcasing a broad number of solutions to very typical use cases for the Go language. There are several examples in the book that are extremely helpful and novel. The book is mostly code, as opposed to narrative, but the narrative included explains what the code samples do and how the work. I would recommend this book to anyone who has gotten started writing Go applications and needs a good base of examples to draw from.
Amazon Verified review Amazon
Mike J. Nov 11, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book provides an excellent corpus of best practices for solving common problems in Go. As a Golang engineer, on topics familiar to me, I found myself affirming the techniques prescribed in this book. It is readily apparent that the author is an expert software engineer and Go developer. On unfamiliar topics, I was able to quickly discern the key points and high level ideas from the author's concise descriptions, consistent layout, and readable code. The book explores a broad set of topics and its layout is ideal for jumping around. The recipe code is well documented and links to additional information are provided for 3rd party libraries and resources. This book can easily serve as the go-to resource for quick introductions and refreshers to the majority of engineering problems that Golang developers encounter. Highly recommended!
Amazon Verified review Amazon
V. B. Rao Oct 02, 2018
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Example, in "Getting and Setting Environment" variables : The author, instead of sticking with built-in Golang features, chooses to use a third-party library, now the code is full of references to this third-party function call. A poor way to describe the subject at hand, and additionally a poor design choice.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.