Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Go Standard Library Cookbook
Go Standard Library Cookbook

Go Standard Library Cookbook: Over 120 specific ways to make full use of the standard library components in Golang

Arrow left icon
Profile Icon Radomír Sohlich
Arrow right icon
€18.99 per month
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1 (1 Ratings)
Paperback Feb 2018 340 pages 1st Edition
eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Radomír Sohlich
Arrow right icon
€18.99 per month
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1 (1 Ratings)
Paperback Feb 2018 340 pages 1st Edition
eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Go Standard Library Cookbook

Interacting with the Environment

In this chapter, the following recipes are covered:

  • Retrieving the Golang version
  • Accessing program arguments
  • Creating a program interface with the flag package
  • Getting and setting environment variables with default values
  • Retrieving the current working directory
  • Getting the current process PID
  • Handling operating system signals
  • Calling an external process
  • Retrieving child process information
  • Reading/writing from the child process
  • Shutting down the application gracefully
  • File configuration with functional options

Introduction

Every program, once it is executed, exists in the environment of the operating system. The program receives input and provides output to this environment. The operating system also needs to communicate with the program to let it know what's happening outside. And finally, the program needs to respond with appropriate actions.

This chapter will walk you through the basics of the discovery of the system environment, the program parameterization via program arguments, and the concept of the operating system signals. You will also learn how to execute and communicate with the child process.

Retrieving the Golang version

While building a program, it is a good practice to log the environment settings, build version, and runtime version, especially if your application is more complex. This helps you to analyze the problem, in case something goes wrong.

Besides the build version and, for example, the environmental variables, the Go version by which the binary was compiled could be included in the log. The following recipe will show you how to include the Go runtime version into such program information.

Getting ready

Install and verify the Go installation. The following steps could help:

  1. Download and install Go on your machine.
  2. Verify that your GOPATH and GOROOT environmental variables are set properly.
  3. Open your Terminal and execute go version. If you get output with a version name, then Go is installed properly.
  4. Create a repository in the GOPATH/src folder.

How to do it...

The following steps cover the solution:

  1. Open the console and create the folder chapter01/recipe01.
  2. Navigate to the directory.
  3. Create the main.go file with the following content:
        package main
import (
"log"
"runtime"
)
const info = `
Application %s starting.
The binary was build by GO: %s`

func main() {
log.Printf(info, "Example", runtime.Version())
}

  1. Run the code by executing the go run main.go.
  2. See the output in the Terminal:

How it works...

The runtime package contains a lot of useful functions. To find out the Go runtime version, the Version function could be used. The documentation states that the function returns the hash of the commit, and the date or tag at the time of the binary build.

The Version function, in fact, returns the runtime/internal/sys .The Version constant. The constant itself is located in the $GOROOT/src/runtime/internal/sys/zversion.go file.

This .go file is generated by the go dist tool and the version is resolved by the findgoversion function in the go/src/cmd/dist/build.go file, as explained next.

The $GOROOT/VERSION takes priority. If the file is empty or does not exist, the $GOROOT/VERSION.cache file is used. If the $GOROOT/VERSION.cache is also not found, the tool tries to resolve the version by using the Git information, but in this case, you need to initialize the Git repository for the Go source.

Accessing program arguments

The most simple way to parameterize the program run is to use the command-line arguments as program parameters.

Simply, the parameterized program call could look like this: ./parsecsv user.csv role.csv. In this case, parsecsv is the name of the executed binary and user.csv and role.csv are the arguments, that modify the program call (in this case it refers to files to be parsed).

How to do it...

  1. Open the console and create the folder chapter01/recipe02.
  2. Navigate to the directory.
  3. Create the main.go file with the following content:
        package main
import (
"fmt"
"os"
)

func main() {

args := os.Args

// This call will print
// all command line arguments.
fmt.Println(args)

// The first argument, zero item from slice,
// is the name of the called binary.
programName := args[0]
fmt.Printf("The binary name is: %s \n", programName)

// The rest of the arguments could be obtained
// by omitting the first argument.
otherArgs := args[1:]
fmt.Println(otherArgs)

for idx, arg := range otherArgs {
fmt.Printf("Arg %d = %s \n", idx, arg) }
}
  1. Build the binary by executing go build -o test.
  2. Execute the command ./test arg1 arg2. (Windows users can run test.exe arg1 arg2).
  3. See the output in the Terminal:

How it works...

The Go standard library offers a few ways to access the arguments of the program call. The most generic way is to access the arguments by the Args variable from the OS package.

This way you can get all the arguments from the command line in a string slice. The advantage of this approach is that the number of arguments is dynamic and this way you can, for example, pass the names of the files to be processed by the program.

The preceding example just echoes all the arguments that are passed to the program. Finally, let's say the binary is called test and the program run is executed by the Terminal command ./test arg1 arg2.

In detail, the os.Args[0] will return ./test. The os.Args[1:] returns the rest of the arguments without the binary name. In the real world, it is better to not rely on the number of arguments passed to the program, but always check the length of the argument array. Otherwise, naturally, if the argument on a given index is not within the range, the program panics.

There's more...

If the arguments are defined as flags, -flag value, additional logic is needed to assign the value to the flag. In this case, there is a better way to parse these by using the flag package. This approach is part of the next recipe.

Creating a program interface with the flag package

The previous recipe describes how to access the program arguments by a very generic approach.

This recipe will provide a way of defining an interface via the program flags. This approach dominates systems based on GNU/Linux, BSD, and macOS. The example of the program call could be ls -l which will, on *NIX systems, list the files in a current directory.

The Go package for flag handling does not support flag combining like ls -ll, where there are multiple flags after a single dash. Each flag must be separate. The Go flag package also does not differentiate between long options and short ones. Finally, -flag and --flag are equivalent.

How to do it...

  1. Open the console and create the folder chapter01/recipe03.
  2. Navigate to the directory.
  3. Create the main.go file with the following content:
        package main
import (
"flag"
"fmt"
"log"
"os"
"strings"
)

// Custom type need to implement
// flag.Value interface to be able to
// use it in flag.Var function.
type ArrayValue []string

func (s *ArrayValue) String() string {
return fmt.Sprintf("%v", *s)
}

func (a *ArrayValue) Set(s string) error {
*a = strings.Split(s, ",")
return nil
}

func main() {

// Extracting flag values with methods returning pointers
retry := flag.Int("retry", -1, "Defines max retry count")

// Read the flag using the XXXVar function.
// In this case the variable must be defined
// prior to the flag.
var logPrefix string
flag.StringVar(&logPrefix, "prefix", "", "Logger prefix")

var arr ArrayValue
flag.Var(&arr, "array", "Input array to iterate through.")

// Execute the flag.Parse function, to
// read the flags to defined variables.
// Without this call the flag
// variables remain empty.
flag.Parse()

// Sample logic not related to flags
logger := log.New(os.Stdout, logPrefix, log.Ldate)

retryCount := 0
for retryCount < *retry {
logger.Println("Retrying connection")
logger.Printf("Sending array %v\n", arr)
retryCount++
}
}
  1. Build the binary by executing the go build -o util.
  2. From the console, execute ./util -retry 2 -prefix=example -array=1,2.
  1. See the output in the Terminal:

How it works...

For the flag definition in code, the flag package defines two types of functions.

The first type is the simple name of the flag type such as Int. This function will return the pointer to the integer variable where the value of the parsed flag is.

The XXXVar functions are the second type. These provide the same functionality, but you need to provide the pointer to the variable. The parsed flag value will be stored in the given variable.

The Go library also supports a custom flag type. The custom type must implement the Value interface from the flag package.

As an example, let's say the flag retry defines the retry limit for reconnecting to the endpoint, the prefix flag defines the prefix of each row in a log, and the array is the array flag that will be send as an payload to server. The program call from the Terminal will look like ./util -retry 2 -prefix=example array=1,2.

The important part of the preceding code is the Parse() function which parses the defined flags from Args[1:]. The function must be called after all flags are defined and before the values are accessed.

The preceding code shows how to parse some data types from the command-line flags. Analogously, the other built-in types are parsed.

The last flag, array, demonstrates the definition of the custom type flag. Note that the ArrayType implements the Value interface from the flag package.

There's more...

The flag package contains more functions to design the interface with flags. It is worth reading the documentation for FlagSet.

By defining the new FlagSet, the arguments could be parsed by calling the myFlagset.Parse(os.Args[2:]). This way you can have flag subsets based on, for example, the first flag.

Getting and setting environment variables with default values

The previous recipe, Creating a program interface with the flag package, describes how to use flags as program parameters.

The other typical way of parameterization, especially for larger applications, is the configuration with the use of environment variables. Environment variables as a configuration option significantly simplify the deployment of the applications. These are also very common in cloud infrastructure.

Usually, the configuration of a database connection for a local and for an automated build environment is different.

If the configuration is defined by the environment variables, it is not necessary to change the application config files or even the application code. The exported environment variables (for example, DBSTRING) are all we need. It is also very practical to default the configuration if the environmental variable is not in place. This way, the life of the application developers is much easier.

This recipe will demonstrate how to read, set and unset the environment variable. It will also show you how to implement the default option if the variable is not set.

How to do it...

  1. Open the console and create the folder chapter01/recipe04.
  2. Navigate to the directory.
  1. Create the get.go file with the following content:
        package main

import (
"log"
"os"
)

func main() {
connStr := os.Getenv("DB_CONN")
log.Printf("Connection string: %s\n", connStr)
}
  1. Execute the code by calling DB_CONN=db:/user@example && go run get.go in the Terminal.
  2. See the output in the Terminal:
  1. Create the lookup.go file with the following content:
        package main

import (
"log"
"os"
)

func main() {

key := "DB_CONN"

connStr, ex := os.LookupEnv(key)
if !ex {
log.Printf("The env variable %s is not set.\n", key)
}
fmt.Println(connStr)
}
  1. Execute the code by calling unset DB_CONN && go run lookup.go in the Terminal.
  2. See the output in the Terminal:
  1. Create the main.go file with the following content:
        package main
import (
"log"
"os"
)

func main() {

key := "DB_CONN"
// Set the environmental variable.
os.Setenv(key, "postgres://as:as@example.com/pg?
sslmode=verify-full")
val := GetEnvDefault(key, "postgres://as:as@localhost/pg?
sslmode=verify-full")
log.Println("The value is :" + val)

os.Unsetenv(key)
val = GetEnvDefault(key, "postgres://as:as@127.0.0.1/pg?
sslmode=verify-full")
log.Println("The default value is :" + val)

}

func GetEnvDefault(key, defVal string) string {
val, ex := os.LookupEnv(key)
if !ex {
return defVal
}
return val
}
  1. Run the code by executing go run main.go.
  2. See the output in the Terminal:

How it works...

The environment variables are accessed by the Getenv and Setenv functions in the os package. The names of the functions are self-explanatory and do not need any further description.

There is one more useful function in the os package. The LookupEnv function provides two values as a result; the value of the variable, and the boolean value which defines if the variable was set or not in the environment.

The disadvantage of the os.Getenv function is that it returns an empty string, even in cases where the environment variable is not set.

This handicap could be overcome by the os.LookupEnv function, which returns the string as a value of the environment variable and the boolean value that indicates whether the variable was set or not.

To implement the retrieval of the environment variable or the default one, use the os.LookupEnv function. Simply, if the variable is not set, which means that the second returned value is false, then the default value is returned. The use of the function is part of step 9.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Develop high quality, fast and portable applications by leveraging the power of Go Standard Library.
  • Practical recipes that will help you work with the standard library algorithms to boost your productivity as a Go developer.
  • Compose your own algorithms without forfeiting the simplicity and elegance of the Standard Library.

Description

Google's Golang will be the next talk of the town, with amazing features and a powerful library. This book will gear you up for using golang by taking you through recipes that will teach you how to leverage the standard library to implement a particular solution. This will enable Go developers to take advantage of using a rock-solid standard library instead of third-party frameworks. The book begins by exploring the functionalities available for interaction between the environment and the operating system. We will explore common string operations, date/time manipulations, and numerical problems. We'll then move on to working with the database, accessing the filesystem, and performing I/O operations. From a networking perspective, we will touch on client and server-side solutions. The basics of concurrency are also covered, before we wrap up with a few tips and tricks. By the end of the book, you will have a good overview of the features of the Golang standard library and what you can achieve with them. Ultimately, you will be proficient in implementing solutions with powerful standard libraries.

Who is this book for?

This book is for Go developers who would like to explore the power of Golang and learn how to use the Go standard library for various functionalities. The book assumes basic Go programming knowledge.

What you will learn

  • Access environmental variables
  • Execute and work with child processes
  • Manipulate strings by performing operations such as search, concatenate, and so on
  • Parse and format the output of date/time information
  • Operate on complex numbers and effective conversions between different number formats and bases
  • Work with standard input and output
  • Handle filesystem operations and file permissions
  • Create TCP and HTTP servers, and access those servers with a client
  • Utilize synchronization primitives
  • Test your code

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 27, 2018
Length: 340 pages
Edition : 1st
Language : English
ISBN-13 : 9781788475273
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Feb 27, 2018
Length: 340 pages
Edition : 1st
Language : English
ISBN-13 : 9781788475273
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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 €5 each
Feature tick icon Exclusive print discounts
€264.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 €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 107.97
Security with Go
€32.99
Distributed Computing with Go
€32.99
Go Standard Library Cookbook
€41.99
Total 107.97 Stars icon

Table of Contents

12 Chapters
Interacting with the Environment Chevron down icon Chevron up icon
Strings and Things Chevron down icon Chevron up icon
Dealing with Numbers Chevron down icon Chevron up icon
Once Upon a Time Chevron down icon Chevron up icon
In and Out Chevron down icon Chevron up icon
Discovering the Filesystem Chevron down icon Chevron up icon
Connecting the Network Chevron down icon Chevron up icon
Working with Databases Chevron down icon Chevron up icon
Come to the Server Side Chevron down icon Chevron up icon
Fun with Concurrency Chevron down icon Chevron up icon
Tips and Tricks Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
(1 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 100%
Leam Hall Oct 15, 2018
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Really didn't get fully past the first chapter. The author has an engaging style and if Packt had done a decent job editing and fixing this could be a classic. When contacted they wanted me to spend time logging all their problems for free. Since there were more than a dozen in Chapter 1 I figured it wasn't worth the time.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.