Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The Go Workshop

You're reading from   The Go Workshop Learn to write clean, efficient code and build high-performance applications with Go

Arrow left icon
Product type Paperback
Published in Dec 2019
Publisher Packt
ISBN-13 9781838647940
Length 824 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (6):
Arrow left icon
Sam Hennessy Sam Hennessy
Author Profile Icon Sam Hennessy
Sam Hennessy
Andrew Hayes Andrew Hayes
Author Profile Icon Andrew Hayes
Andrew Hayes
Gobin Sougrakpam Gobin Sougrakpam
Author Profile Icon Gobin Sougrakpam
Gobin Sougrakpam
Jeremy Leasor Jeremy Leasor
Author Profile Icon Jeremy Leasor
Jeremy Leasor
Delio D'Anna Delio D'Anna
Author Profile Icon Delio D'Anna
Delio D'Anna
Dániel Szabó Dániel Szabó
Author Profile Icon Dániel Szabó
Dániel Szabó
+2 more Show less
Arrow right icon
View More author details
Toc

Table of Contents (21) Chapters Close

Preface 1. Variables and Operators FREE CHAPTER 2. Logic and Loops 3. Core Types 4. Complex Types 5. Functions 6. Errors 7. Interfaces 8. Packages 9. Basic Debugging 10. About Time 11. Encoding and Decoding (JSON) 12. Files and Systems 13. SQL and Databases 14. Using the Go HTTP Client 15. HTTP Servers 16. Concurrent Work 17. Using Go Tools 18. Security 19. Special Features Appendix

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 }

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:

  1. Once it's installed, open Visual Studio Code.
  2. From the top menu bar, select View.
  3. From the list of options, select Extensions.
  4. A panel should appear on the left side. At the top is a search input box.
  5. Type Go.
  6. The first option should be an extension called Go by Microsoft.
  7. Click the Install button on that option.
  8. Wait for a message that says it's successfully installed.

If you have Git installed, follow these steps:

  1. Press Ctrl/Cmd + Shift + P all at the same time.A text input should appear at the top of the window.
  2. Type go tools.
  3. Select the option labeled something like Go: Install/Update Tools.
  4. You'll see a list of options and checkboxes.
  5. 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.
  6. 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

  1. In your editor, create a new folder called test.
  2. In the folder, create a file called main.go.
  3. Copy and paste the following code into the file you just created:
    package main
    import (
        "fmt"
    )
    func main() {
        fmt.Println("This is a test")
    }
  4. Save the file.
  5. Open a terminal and go into the test folder.
  6. If you are using Visual Studio Code:
    • Select Terminal from the top menu bar.
    • From the options, select New Terminal.
    • Type cd test.
  7. In the terminal, type go build.
  8. This should run quickly and finish without displaying any messages.
  9. 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 called test.exe. This file is your binary.
  10. Now let's run our application by executing our binary. Type ./test.
  11. 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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image