About the Book
The Go Workshop will take the pain out of learning the Go programming language (also known as Golang). It is designed to teach you to be productive in building real-world software. Presented in an engaging, hands-on way, this book focuses on the features of Go that are used by professionals in their everyday work.
Each concept is broken down, clearly explained, and followed up with activities to test your knowledge and build your practical skills.
Your first steps will involve mastering Go syntax, working with variables and operators, and using core and complex types to hold data. Moving ahead, you will build your understanding of programming logic and implement Go algorithms to construct useful functions.
As you progress, you'll discover how to handle errors, debug code to troubleshoot your applications, and implement polymorphism using interfaces. The later chapters will then teach you how to manage files, connect to a database, work with HTTP servers and REST APIs, and make use of concurrent programming.
Throughout this Workshop, you'll work on a series of mini projects, including a shopping cart, a loan calculator, a working hours tracker, a web page counter, a code checker, and a user authentication system.
By the end of this book, you'll have the knowledge and confidence to tackle your own ambitious projects with Go.
About the Chapters
Chapter 1, Variables and Operators, explains how variables hold data for you temporarily. It also shows how you can use operators to make changes or make comparisons to that data.
Chapter 2, Logic and Loops, teaches you how to make your code dynamic and responsive by creating rules that must be followed based on data in variables. Loops let you repeat logic over and over again.
Chapter 3, Core Types, introduces you to the building blocks of data. You'll learn what a type is and how the core types are defined.
Chapter 4, Complex Types, explains that complex types build on core types to allow you to model real-world data using data grouping and by composing new types from the core types. You'll also look at overcoming Go's type system when needed.
Chapter 5, Functions, teaches you the basics of constructing a function. Then, we will dive into more advanced features of using functions, such as passing a function as an argument, returning a function, assigning a function to a variable, and many more interesting things you can do with functions.
Chapter 6, Errors, teaches you how to work with errors, covering topics such as declaring your own error and handling errors the Go way. You will learn what a panic is and how to recover from one.
Chapter 7, Interfaces, starts by teaching the mechanics of interfaces and then demonstrates that interfaces in Go offer polymorphism, duck typing, the ability to have empty interfaces, and the implicit implementation of an interface.
Chapter 8, Packages, demonstrates how the Go standard library organizes its code and how you can do the same for your code.
Chapter 9, Basic Debugging, teaches the fundamentals of finding bugs in our application. You will use various techniques of printing out markers in code, using values and types, and performing logging.
Chapter 10, About Time, gets you a head start in the concept of how Go manages time variables, and what features are provided for you to improve your applications, such as measuring execution time and navigating between time zones.
Chapter 11, Encoding and Decoding (JSON), teaches you the fundamentals of a JSON document, which is heavily used throughout various parts of software today, along with the great support that Go has for reading and creating JSON documents.
Chapter 12, Files and Systems, shows how Go has great support for working with files and the underlying OS. You will be working with the filesystem, learning how to create, read, and modify files on the OS. You will also see how Go can read a CSV file, a common file format used by administrators.
Chapter 13, SQL and Databases, covers the most important aspects of connecting to databases and manipulating tables, which are very common tasks nowadays, and you'll learn how to work efficiently with databases.
Chapter 14, Using the Go HTTP Client, instructs you how to use the Go standard packages to create an HTTP client and interact with REST APIs. You'll learn how to send GET requests to a server and process the response, as well as how to POST form data to a server and how to upload a file to a server.
Chapter 15, HTTP Servers, teaches you how to use the Go standard packages to create an HTTP server and build websites and REST APIs on top of it. You'll learn how to accept requests from a web form or from another program and respond in a human- or machine-readable format.
Chapter 16, Concurrent Work, demonstrates how to make use of Go's concurrency features to enable your software to perform several tasks at the same time, splitting the work across independent routines and reducing the processing time.
Chapter 17, Using Go Tools, familiarizes you with the tools that come with Go and explains how you can use them to improve your code. You'll learn how to automatically format your code with gofmt and goimports. You'll also learn how to do static analysis with go vet and how to detect race conditions using the Go race detector.
Chapter 18, Security, builds your understanding of how to identify and fix security attacks such as SQL injection and cross-site scripting. You'll learn how to use the Go standard package to implement symmetric and asymmetric encryption, and how to secure data at rest and data in transit using hashing libraries and the TLS package in Go.
Chapter 19, Special Features, lets you explore some hidden gems in Go that will make development easier. You will learn how to use build constraints to control application build behavior. You will also learn how to use the wildcard pattern with Go and how to use reflection in Go using the reflect package. This chapter will also build your understanding of how to access the runtime memory of your application using the unsafe package.
Conventions
Code words in text, database table names, folder names, filenames, file extensions, path names, dummy URLs, user input, and Twitter handles are shown as follows:
"A panic()
function accepts an empty interface."
Words that you see on the screen, for example, in menus or dialog boxes, also appear in the same format.
A block of code is set as follows:
type error interface { Â Error()string }
New terms and important words are shown like this: "These behaviors are collectively called method sets."
Long code snippets are truncated and the corresponding names of the code files on GitHub are placed at the top of the truncated code. The permalinks to the entire code are placed below the code snippet. It should look as follows:
main.go
6Â Â func main() { 7Â Â Â Â a() 8Â Â Â Â fmt.Println("This line will now get printed from main() function") 9Â Â } 10Â func a() { 11Â Â Â b("good-bye") 12Â Â Â fmt.Println("Back in function a()") 13Â }
The full code for this step is available at https://packt.live/2E6j6ig
Before You Begin
Each great journey begins with a humble step. Our upcoming adventure with Go programming is no exception. Before we can do awesome things using Go, we need to be prepared with a productive environment. In this small note, we shall see how to do that.
Hardware and Software Recommendations for Windows with Docker
To be able to run all the recommended tools used in the course, it's recommended that you have:
- 1.6 GHz or faster desktop (amd64, 386) processor.
- 4 GB of RAM.
- Windows 10 64-bit: Pro, Enterprise, or Education (1607 Anniversary Update, Build 14393 or later).
- You must have virtualization enabled in BIOS, which is usually enabled by default. Virtualization is different from having Hyper-V enabled.
- CPU SLAT-capable feature.
Hardware and Software Recommendations for Windows without Docker
If the system you are using is below the recommended requirements to use with Docker, you can still do the course. You have to complete an extra step to do so.
To be able to run all the tools (excluding Docker), you'll need:
- 1.6 GHz or faster desktop (amd64, 386) processor
- 1 GB of RAM
- Windows 7 (with .NET Framework 4.5.2), 8.0, 8.1, or 10 (32-bit and 64-bit)
Skip the steps, which explain how to install Docker. You'll need to install the MySQL server instead. You can download an installer from https://packt.live/2EQkiHe. The default options are safe to use if you are not sure which to pick. MySQL is free to install and use.
Once the course is complete, you can safely uninstall MySQL.
Hardware and Software Recommendations for macOS with Docker
To be able to run all the recommended tools used in the course, it's recommended that you have:
- 1.6 GHz or faster desktop (amd64, 386) processor
- 4 GB of RAM
- macOS X or newer, with Intel's hardware Memory Management Unit (MMU)
- macOS Sierra 10.12 or newer
Hardware and Software Recommendations for macOS without Docker
- If the system you are using is below the recommended requirements to use with Docker, you can still do the course. You need to complete an extra step to do so.
- To be able to run all the tools (excluding Docker), you'll need:
- 1.6 GHz or faster desktop (amd64, 386) processor
- 1 GB of RAM
- macOS Yosemite 10.10 or newer
Skip the steps, which explain how to install Docker. You'll need to install the MySQL server instead. You can download an installer from https://packt.live/2EQkiHe. The default options are safe to use if you are not sure which to pick. MySQL is free to install and use.
Once the course is complete, you can safely uninstall MySQL.
Hardware and Software Recommendations for Linux
To be able to run all the recommended tools used in the course, it's recommended that you have:
- 1.6 GHz or faster desktop (amd64, 386) processor
- 1 GB of RAM
- Linux (Debian): Ubuntu Desktop 14.04, Debian 7
- Linux (Red Hat): Red Hat Enterprise Linux 7, CentOS 7, Fedora 23
Install the Go Compiler
To turn your Go source code into something you can run, you'll need the Go compiler. For Windows and macOS, we recommend using the installer. Alternatively, to get more control you can download precompiled binaries. You can find both at https://packt.live/2PRUGjp. The install instructions for both methods on Windows, macOS, and Linux are at https://packt.live/375DQDA. The Go compiler is free to download and use.
Install Git
Go uses the version control tool Git to install extra tools and code. You can find the instructions for Windows, macOS, and Linux at https://packt.live/35ByRug. Git is free to install and use.
Install Visual Studio Code (Editor/IDE)
You need something to write your Go source code. This tool is called an editor or an Integrated Development Environment (IDE). If you already have an editor you like, you can use it with this course if you'd like to.
If you don't already have an editor, we recommend you use the free editor Visual Studio Code. You can download the installer from https://packt.live/35KD2Ek:
- Once it's installed, open Visual Studio Code.
- From the top menu bar, select
View
. - From the list of options, select
Extensions
. - A panel should appear on the left side. At the top is a search input box.
- Type
Go
. - The first option should be an extension called Go by Microsoft.
- Click the Install button on that option.
- Wait for a message that says it's successfully installed.
If you have Git installed, follow these steps:
- Press Ctrl/Cmd + Shift + P all at the same time.A text input should appear at the top of the window.
- Type
go tools
. - Select the option labeled something like
Go: Install/Update Tools
. - You'll see a list of options and checkboxes.
- The very first checkbox next to the search input checks all the checkboxes. Select this checkbox, then select the
Go
button to the right of it. - A panel from the bottom should appear with some activity in it. Once this stops (and it may take a few minutes), you're all done.
Once done, select View
from the top menu bar, then select Explorer
.
You'll now need somewhere to put your Go projects. I recommend somewhere in your home directory. Avoid putting it in the Go path, which is the folder the Go compiler is installed in. If you are having problems with the modules
later in the class, it may be due to this. Once you know where you want to store the projects, create a folder for them. It's essential that you can find your way back to this folder.
In Visual Studio Code, select the Open Folder button. From the dialog that opens, select the folder you just created.
Create a Test Application
- In your editor, create a new folder called
test
. - In the folder, create a file called
main.go
. - Copy and paste the following code into the file you just created:
package main import ( "fmt" ) func main() { fmt.Println("This is a test") }
- Save the file.
- Open a terminal and go into the
test
folder. - If you are using Visual Studio Code:
- Select
Terminal
from the top menu bar. - From the options, select
New Terminal
. - Type
cd test
.
- Select
- In the terminal, type
go build
. - This should run quickly and finish without displaying any messages.
- You should now see a new file in that same folder. On Linux and macOS, you'll have a file named
test
. On Windows, you'll have one calledtest.exe
. This file is your binary. - Now let's run our application by executing our binary. Type
./test
. - You should see the message
This is a test
. If you see the message, you have successfully set up your Go development environment.
Install Docker
If your computer can run it (see the Hardware and Software Requirements section), you should install Docker. Docker allows us to run things such as database servers without having to install them. Docker is free to install and use.
We only use Docker to run MySQL for the database part of the course. If you already have MySQL installed, then you can skip this part.
For macOS users, follow the instructions at https://packt.live/34VJLJD.
For Windows users, follow the instructions at https://packt.live/2EKGDG6.
Linux users, you should be able to use your built-in package manager to install Docker. Instructions for common distributions are at https://packt.live/2Mn8Cjc.
You are safe to uninstall Docker, if you wish, once the course is complete.
Installing the Code Bundle
Download the code files from GitHub at and place them in a new folder called C:\Code
. Refer to these code files for the complete code bundle at https://packt.live/2ZmmZJL.