Go Standard Library Cookbook
eBook - ePub

Go Standard Library Cookbook

  1. English
  2. ePUB (mobile friendly)
  3. Available on iOS & Android
eBook - ePub

Go Standard Library Cookbook

Book details
Book preview
Table of contents
Citations

About This Book

Implement solutions by leveraging the power of the GO standard library and reducing dependency on external cratesAbout This Bookā€¢ 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.Who This Book Is ForThis 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 codeIn DetailGoogle'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.Style and approachSolution based approach showcasing the power of Go standard library for easy practical implementations.

Frequently asked questions

Simply head over to the account section in settings and click on ā€œCancel Subscriptionā€ - itā€™s as simple as that. After you cancel, your membership will stay active for the remainder of the time youā€™ve paid for. Learn more here.
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
Both plans give you full access to the library and all of Perlegoā€™s features. The only differences are the price and subscription period: With the annual plan youā€™ll save around 30% compared to 12 months on the monthly plan.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, weā€™ve got you covered! Learn more here.
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Yes, you can access Go Standard Library Cookbook by Radomir Sohlich in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming Languages. We have over one million books available in our catalogue for you to explore.

Information

Year
2018
ISBN
9781788391672
Edition
1

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

Table of contents

  1. Title Page
  2. Copyright and Credits
  3. Packt Upsell
  4. Contributors
  5. Preface
  6. Interacting with the Environment
  7. Strings and Things
  8. Dealing with Numbers
  9. Once Upon a Time
  10. In and Out
  11. Discovering the Filesystem
  12. Connecting the Network
  13. Working with Databases
  14. Come to the Server Side
  15. Fun with Concurrency
  16. Tips and Tricks
  17. Other Books You May Enjoy