The Go Workshop

Book description

Get started with Go and learn how to leverage its simplicity and flexibility to solve real-world problems and build practical software

Key Features

  • Build a comprehensive foundation in Go and focus on developing real-world applications
  • Explore the Go Standard Library and learn how to structure your code
  • Learn how to efficiently interact with files, databases and REST APIs

Book Description

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.

What you will learn

  • Understand Go syntax and use it to handle data and write functions
  • Debug your Go code to troubleshoot development problems
  • Safely handle errors and recover from panics
  • Implement polymorphism by using interfaces
  • Work with files and connect to external databases
  • Create a HTTP client and server and work with a RESTful web API
  • Use concurrency to design software that can multitask
  • Use Go Tools to simplify development and improve your code

Who this book is for

The Go Workshop is designed for anyone who is new to Go. Whether you're beginning your journey as an aspiring developer, or are experienced with another programming language and want to branch out to something new, this book will get you on the right track. No prior programming experience is necessary.

Table of contents

  1. Preface
    1. About the Book
      1. About the Chapters
      2. Conventions
      3. Before You Begin
      4. Hardware and Software Recommendations for Windows with Docker
      5. Hardware and Software Recommendations for Windows without Docker
      6. Hardware and Software Recommendations for macOS with Docker
      7. Hardware and Software Recommendations for macOS without Docker
      8. Hardware and Software Recommendations for Linux
      9. Install the Go Compiler
      10. Install Git
      11. Install Visual Studio Code (Editor/IDE)
      12. Create a Test Application
      13. Install Docker
      14. Installing the Code Bundle
  2. 1. Variables and Operators
    1. Introduction
      1. What Does Go Look Like?
      2. Exercise 1.01: Using Variables, Packages, and Functions to Print Stars
      3. Activity 1.01 Defining and Printing
      4. Declaring Variables
      5. Declaring a Variable Using var
      6. Exercise 1.02: Declaring a Variable Using var
      7. Declaring Multiple Variables at Once with var
      8. Exercise 1.03: Declaring Multiple Variables at Once with var
      9. Skipping the Type or Value When Declaring Variables
      10. Exercise 1.04: Skipping the Type or Value When Declaring Variables
      11. Type Inference Gone Wrong
      12. Short Variable Declaration
      13. Exercise 1.05: Implementing Short Variable Declaration
      14. Declaring Multiple Variables with a Short Variable Declaration
      15. Exercise 1.06: Declaring Multiple Variables from a Function
      16. Using var to Declare Multiple Variables in One Line
      17. Non-English Variable Names
      18. Changing the Value of a Variable
      19. Exercise 1.07: Changing the Value of a Variable
      20. Changing Multiple Values at Once
      21. Exercise 1.08: Changing Multiple Values at Once
      22. Operators
      23. Exercise 1.09 Using Operators with Numbers
      24. Shorthand Operator
      25. Exercise 1.10: Implementing Shorthand Operators
      26. Comparing Values
      27. Exercise 1.11: Comparing Values
      28. Zero Values
      29. Exercise 1.12 Zero Values
      30. Value versus Pointer
      31. Getting a Pointer
      32. Exercise 1.13: Getting a Pointer
      33. Getting a Value from a Pointer
      34. Exercise 1.14: Getting a Value from a Pointer
      35. Function Design with Pointers
      36. Exercise 1.15: Function Design with Pointers
      37. Activity 1.02: Pointer Value Swap
      38. Constants
      39. Exercise 1.16: Constants
      40. Enums
      41. Scope
      42. Activity 1.03: Message Bug
      43. Activity 1.04: Bad Count Bug
    2. Summary
  3. 2. Logic and Loops
    1. Introduction
      1. if Statements
      2. Exercise 2.01: A Simple if Statement
      3. if else Statements
      4. Exercise 2.02: Using an if else Statement
      5. else if Statements
      6. Exercise 2.03: Using an else if Statement
      7. The Initial if Statement
      8. Exercise 2.04: Implementing the Initial if Statements
      9. Activity 2.01: Implementing FizzBuzz
      10. Expression switch Statements
      11. Exercise 2.05: Using a switch Statement
      12. Exercise 2.06: switch Statements and Multiple case Values
      13. Exercise 2.07: Expressionless switch Statements
      14. Loops
      15. Exercise 2.08: Using the for i Loop
      16. Exercise 2.09: Looping Over Arrays and Slices
      17. The range Loop
      18. Exercise 2.10: Looping Over a Map
      19. Activity 2.02: Looping Over Map Data Using range
      20. break and continue
      21. Exercise 2.11: Using break and continue to Control Loops
      22. Activity 2.03: Bubble Sort
    2. Summary
  4. 3. Core Types
    1. Introduction
    2. True and False
      1. Exercise 3.01: Program to Measure Password Complexity
    3. Numbers
      1. Integer
      2. Floating Point
      3. Exercise 3.02: Floating-Point Number Accuracy
      4. Overflow and Wraparound
      5. Exercise 3.03: Triggering Number Wraparound
      6. Big Numbers
      7. Exercise 3.04: Big Numbers
    4. Byte
    5. Text
      1. Rune
      2. Exercise 3.05: Safely Looping over a String
    6. The nil Value
      1. Activity 3.01: Sales Tax Calculator
      2. Activity 3.02: Loan Calculator
    7. Summary
  5. 4. Complex Types
    1. Introduction
    2. Collection Types
    3. Arrays
      1. Exercise 4.01: Defining an Array
      2. Comparing Arrays
      3. Exercise 4.02: Comparing Arrays
      4. Initializing Arrays Using Keys
      5. Exercise 4.03: Initializing an Array Using Keys
      6. Reading from an Array
      7. Exercise 4.04: Reading a Single Item from an Array
      8. Writing to an Array
      9. Exercise 4.05: Writing to an Array
      10. Looping an Array
      11. Exercise 4.06: Looping Over an Array Using a "for i" Loop
      12. Modifying the Contents of an Array in a Loop
      13. Exercise 4.07: Modifying the Contents of an Array in a Loop
      14. Activity 4.01: Filling an Array
    4. Slice
      1. Exercise 4.08: Working with Slices
      2. Activity 4.02: Printing a User's Name Based on User Input
      3. Appending Multiple Items to a Slice
      4. Exercise 4.09: Appending Multiple Items to a Slice
      5. Activity 4.03: Creating a Locale Checker
      6. Creating Slices from Slices and Arrays
      7. Exercise 4.10: Creating Slices from a Slice
      8. Understanding Slice Internals
      9. Exercise 4.11: Using make to Control the Capacity of a Slice
      10. Background Behavior of Slices
      11. Exercise 4.12: Controlling Internal Slice Behavior
      12. Map Fundamentals
      13. Exercise 4.13: Creating, Reading, and Writing a Map
      14. Reading from Maps
      15. Exercise 4.14: Reading from a Map
      16. Activity 4.04: Slicing the Week
      17. Deleting Elements from a Map
      18. Exercise 4.15: Deleting an Element from a Map
      19. Activity 4.05: Removing an Element from a Slice
    5. Simple Custom Types
      1. Exercise 4.16: Creating a Simple Custom Type
    6. Structs
      1. Exercise 4.17: Creating Struct Types and Values
      2. Comparing Structs to Each Other
      3. Exercise 4.18: Comparing Structs to Each Other
      4. Struct Composition Using Embedding
      5. Exercise 4.19: Struct Embedding and Initialization
      6. Type Conversions
      7. Exercise 4.20: Numeric Type Conversion
      8. Type Assertions and interface{}
      9. Exercise 4.21: Type Assertion
      10. Type Switch
      11. Exercise 4.22: Type Switch
      12. Activity 4.06: Type Checker
    7. Summary
  6. 5. Functions
    1. Introduction
    2. Functions
      1. Parts of a function
    3. fizzBuzz
      1. Exercise 5.01: Creating a Function to Print Salesperson Expectation Ratings from the Number of Items Sold
    4. Parameters
      1. The Difference between an Argument and a Parameter
      2. Exercise 5.02: Mapping Index Values to Column Headers
      3. Function Variable Scope
      4. Return Values
      5. Exercise 5.03: Creating a fizzBuzz Function with Return Values
      6. Activity 5.01: Calculating the Working Hours of Employees
    5. Naked Returns
      1. Exercise 5.04: Mapping a CSV Index to a Column Header with Return Values
      2. Variadic Function
      3. Exercise 5.05: Summing Numbers
      4. Anonymous Functions
      5. Exercise 5.06: Creating an Anonymous Function to Calculate the Square Root of a Number
    6. Closures
      1. Exercise 5.07: Creating a Closure Function to Decrement a Counter
      2. Function Types
      3. Exercise 5.08: Creating Various Functions to Calculate Salary
    7. defer
      1. Activity 5.02: Calculating Payable Amount for Employees Based on Working Hours
    8. Summary
  7. 6. Errors
    1. Introduction
    2. What Are Errors?
      1. Syntax Errors
      2. Runtime Errors
      3. Exercise 6.01: Runtime Errors While Adding Numbers
      4. Semantic Errors
      5. Exercise 6.02: Logic Error with Walking Distance
    3. Error Handling Using Other Programming Languages
    4. Error Interface Type
      1. Creating Error Values
      2. Exercise 6.03: Creating an Application to Calculate Pay for the Week
    5. Panic
      1. Exercise 6.04: Crashing the Program on Errors Using panic
    6. Recover
      1. Exercise 6.05: Recovering from a Panic
      2. Guidelines when working with Errors and Panic
      3. Activity 6.01: Creating a Custom Error Message for a Banking Application
      4. Activity 6.02: Validating a Bank Customer's Direct Deposit Submission
      5. Activity 6.03: Panic on Invalid Data Submission
      6. Activity 6.04: Preventing a Panic from Crashing the App
    7. Summary
  8. 7. Interfaces
    1. Introduction
    2. Interface
      1. Defining an Interface
      2. Implementing an Interface
      3. Advantages of Implementing Interfaces Implicitly
      4. Exercise 7.01: Implementing an Interface
    3. Duck Typing
    4. Polymorphism
      1. Exercise 7.02: Calculating the Area of Different Shapes Using Polymorphism
    5. Accepting Interfaces and Returning Structs
      1. Empty interface{}
      2. Type Assertion and Switches
      3. Exercise 7.03: Analyzing Empty interface{} Data
      4. Activity 7.01: Calculating Pay and Performance Review
    6. Summary
  9. 8. Packages
    1. Introduction
      1. Maintainable
        1. Reusable
        2. Modular
    2. What Is a Package?
      1. Package Structure
      2. Package Naming
      3. Package Declarations
    3. Exported and Unexported Code
      1. GOROOT and GOPATH
      2. Package Alias
      3. Main Package
      4. Exercise 8.01: Creating a Package to Calculate Areas of Various Shapes
    4. The init() Function
      1. Exercise 8.02: Loading Budget Categories
      2. Executing Multiple init() Functions
      3. Exercise 8.03: Assigning Payees to Budget Categories
      4. Activity 8.01: Creating a Function to Calculate Payroll and Performance Review
    5. Summary
  10. 9. Basic Debugging
    1. Introduction
    2. Methods for Bug-Free Code
      1. Code Incrementally and Test Often
      2. Writing Unit Tests
      3. Handling All Errors
      4. Performing Logging
      5. Formatting Using fmt
      6. Exercise 9.01: Working with fmt.Println
      7. Formatting Using fmt.Printf()
      8. Additional Options for Formatting
      9. Exercise 9.02: Printing Decimal, Binary, and Hex Values
    3. Basic Debugging
      1. Printing Go Variable Types
      2. Exercise 9.03 Printing the Go Representation of a Variable
    4. Logging
    5. Log Fatal Errors
      1. Activity 9.01: Building a Program to Validate Social Security Numbers
    6. Summary
  11. 10. About Time
    1. Introduction
    2. Making Time
      1. Exercise 10.1: Creating a Function to Return a timestamp
    3. Comparing Time
    4. Duration Calculation
    5. Managing Time
      1. Exercise 10.2: Duration of Execution
    6. Formatting Time
      1. Exercise 10.03: What Is the Time in Your Zone?
      2. Activity 10.01: Formatting a Date According to User Requirements
      3. Activity 10.02: Enforcing a Specific Format of Date and Time
      4. Activity 10.03: Measuring Elapsed Time
      5. Activity 10.04: Calculating the Future Date and Time
      6. Activity 10.05: Printing the Local Time in Different Time Zones
    7. Summary
  12. 11. Encoding and Decoding (JSON)
    1. Introduction
    2. JSON
    3. Decoding JSON
      1. Struct Tags
      2. Exercise 11.01: Unmarshaling Student Courses
    4. Encoding JSON
      1. Exercise 11.02: Marshaling Student Courses
      2. Unknown JSON Structures
      3. Exercise 11.03: Analyzing College Class JSON
    5. GOB: Go's Own Encoding
      1. Exercise 11.04: Using gob to Encode Data
      2. Activity 11.01: Mimicking a Customer Order Using JSON
    6. Summary
  13. 12. Files and Systems
    1. Introduction
    2. Filesystem
      1. File Permissions
    3. Flags and Arguments
      1. Signals
      2. Exercise 12.01: Simulating Cleanup
    4. Creating and Writing to Files
      1. Reading the Whole File at Once
      2. Exercise 12.02: Backing Up Files
    5. CSV
      1. Activity 12.01: Parsing Bank Transaction Files
    6. Summary
  14. 13. SQL and Databases
    1. Introduction
    2. The Database
    3. Database API and Drivers
    4. Connecting to Databases
    5. Creating Tables
    6. Inserting Data
      1. Exercise 13.01: Creating a Table with Numbers
    7. Retrieving Data
    8. Updating Existing Data
    9. Deleting Data
      1. Exercise 13.02: Holding Prime Numbers in a Database
    10. Truncating and Deleting Table
      1. Activity 13.01: Holding User Data in a Table
      2. Activity 13.02: Finding Messages of Specific Users
    11. Summary
  15. 14. Using the Go HTTP Client
    1. Introduction
    2. The Go HTTP Client and Its Uses
    3. Sending a Request to a Server
      1. Exercise 14.01: Sending a Get Request to a Web Server Using the Go HTTP Client
    4. Structured Data
      1. Exercise 14.02: Using the HTTP Client with Structured Data
      2. Activity 14.01: Requesting Data from a Web Server and Processing the Response
    5. Sending Data to a Server
      1. Exercise 14.03: Sending a Post Request to a Web Server Using the Go HTTP Client
      2. Uploading Files in a Post Request
      3. Exercise 14.04: Uploading a File to a Web Server via a Post Request
      4. Custom Request Headers
      5. Exercise 14.05: Using Custom Headers and Options with the Go HTTP Client
      6. Activity 14.02: Sending Data to a Web Server and Checking Whether the Data Was Received Using POST and GET
    6. Summary
  16. 15. HTTP Servers
    1. Introduction
    2. How to Build a Basic Server
    3. HTTP Handler
      1. Exercise 15.01: Creating a Hello World Server
    4. Simple Routing
      1. Exercise 15.02: Routing Our Server
    5. Handler versus Handler Function
      1. Activity 15.01: Adding a Page Counter to an HTML Page
    6. Returning Complex Structures
      1. Activity 15.02: Serving a Request with a JSON Payload
    7. Dynamic Content
      1. Exercise 15.03: Personalized Welcome
    8. Templating
      1. Exercise 15.04: Templating Our Pages
    9. Static Resources
      1. Exercise 15.05: Creating a Hello World Server Using a Static File
    10. Getting Some Style
      1. Exercise 15.06: A Stylish Welcome
    11. Getting Dynamic
      1. Activity 15.03: External Template
    12. HTTP Methods
      1. Exercise 15.07: Completing a Questionnaire
    13. JSON loads
      1. Exercise 15.08: Building a Server That Accepts JSON Requests
    14. Summary
  17. 16. Concurrent Work
    1. Introduction
    2. Goroutines
      1. Exercise 16.01: Using Concurrent Routines
    3. WaitGroup
      1. Exercise 16.02: Experimenting with WaitGroup
    4. Race Conditions
    5. Atomic Operations
      1. Exercise 16.03: An Atomic Change
    6. Invisible Concurrency
      1. Activity 16.01: Listing Numbers
    7. Channels
      1. Exercise 16.04: Exchange Greeting Messages via Channels
      2. Exercise 16.05: Two-Way Message Exchange with Channels
      3. Exercise 16.06: Sum Numbers from Everywhere
      4. Exercise 16.07: Request to Goroutines
    8. The Importance of Concurrency
      1. Exercise 16.08: Equally Splitting the Work between Routines
    9. Concurrency Patterns
      1. Activity 16.02: Source Files
    10. Buffers
      1. Exercise 16.09: Notifying When Computation Has Finished
      2. Some More Common Practices
    11. HTTP Servers
    12. Methods as Routines
      1. Exercise 16.10: A Structured Work
    13. Go Context Package
      1. Exercise 16.11: Managing Routines with Context
    14. Summary
  18. 17. Using Go Tools
    1. Introduction
    2. The go build Tool
      1. Exercise 17.01: Using the go build Tool
    3. The go run Tool
      1. Exercise 17.02: Using the go run Tool
    4. The gofmt Tool
      1. Exercise 17.03: Using the gofmt Tool
    5. The goimports Tool
      1. Exercise 17.04: Using the goimports Tool
    6. The go vet Tool
      1. Exercise 17.05: Using the go vet Tool
    7. The Go Race Detector
      1. Exercise 17.06: Using the Go Race Detector
    8. The go doc Tool
      1. Exercise 17.07: Implementing the go doc Tool
    9. The go get Tool
      1. Exercise 17.08: Implementing the go get Tool
      2. Activity 17.01: Using gofmt, goimport, go vet, and go get to Correct a File
    10. Summary
  19. 18. Security
    1. Introduction
    2. Application Security
      1. SQL Injection
      2. Command Injection
      3. Exercise 18.01: Handling SQL Injection
    3. Cross-Site Scripting
      1. Exercise 18.02: Handling XSS Attacks
    4. Cryptography
      1. Hashing Libraries
      2. Exercise 18.03: Using Different Hashing Libraries
    5. Encryption
      1. Symmetric Encryption
      2. Exercise 18.04: Symmetric Encryption and Decryption
      3. Asymmetric Encryption
      4. Exercise 18.05: Asymmetric Encryption and Decryption
    6. Random Generators
      1. Exercise 18.06: Random Generators
    7. HTTPS/TLS
      1. Exercise 18.07: Generating a Certificate and Private Key
      2. Exercise 18.08: Running an HTTPS Server
    8. Password Management
      1. Activity 18.01: Authenticating Users on the Application Using Hashed Passwords
      2. Activity 18.02: Creating CA Signed Certificates Using Crypto Libraries
    9. Summary
  20. 19. Special Features
    1. Introduction
    2. Build Constraints
      1. Build Tags
      2. Filenames
    3. Reflection
    4. TypeOf and ValueOf
      1. Exercise 19.01: Using Reflection
      2. Activity 19.01: Defining Build Constraints Using Filenames
    5. DeepEqual
    6. Wildcard Pattern
    7. The unsafe Package
      1. Exercise 19.02: Using cgo with unsafe
      2. Activity 19.02: Using Wildcard with Go Test
    8. Summary
  21. Appendix
    1. 1. Variables and Operators
      1. Activity 1.01 Defining and Printing
      2. Activity 1.02: Pointer Value Swap
      3. Activity 1.03: Message Bug
      4. Activity 1.04: Bad Count Bug
    2. 2. Logic and Loops
      1. Activity 2.01: Implementing FizzBuzz
      2. Activity 2.02: Looping Over Map Data Using range
      3. Activity 2.03: Bubble Sort
    3. 3. Core Types
      1. Activity 3.01: Sales Tax Calculator
      2. Activity 3.02: Loan Calculator
    4. 4. Complex Types
      1. Activity 4.01: Filling an Array
      2. Activity 4.02: Printing a User's Name Based on User Input
      3. Activity 4.03: Creating a Locale Checker
      4. Activity 4.04: Slicing the Week
      5. Activity 4.05: Removing an Element from a Slice
      6. Activity 4.06: Type Checker
    5. 5. Functions
      1. Activity 5.01: Calculating the Working Hours of Employees
      2. Activity 5.02: Calculating Payable Amount for Employees Based on Working Hours
    6. 6. Errors
      1. Activity 6.01: Creating a Custom Error Message for a Banking Application
      2. Activity 6.02: Validating a Bank Customer's Direct Deposit Submission
      3. Activity 6.03: Panic on Invalid Data Submission
      4. Activity 6.04: Preventing a Panic from Crashing the App
    7. 7. Interfaces
      1. Activity 7.01: Calculating Pay and Performance Review
    8. 8. Packages
      1. Activity 8.01: Creating a Function to Calculate Payroll and Performance Review
    9. 9. Basic Debugging
      1. Activity 9.01: Building a Program to Validate Social Security Numbers
    10. 10. About Time
      1. Activity 10.01: Formatting a Date According to User Requirements
      2. Activity 10.02: Enforcing a Specific Format of Date and Time
      3. Activity 10.03: Measuring Elapsed Time
      4. Activity 10.04: Calculating the Future Date and Time
      5. Activity 10.05: Printing the Local Time in Different Time Zones
    11. 11. Encoding and Decoding (JSON)
      1. Activity 11.01: Mimicking a Customer Order Using JSON
    12. 12. Files and Systems
      1. Activity 12.01: Parsing Bank Transaction Files
    13. 13. SQL and Databases
      1. Activity 13.1: Holding User Data in a Table
      2. Activity 13.2: Finding Messages of Specific Users
    14. 14. Using the Go HTTP Client
      1. Activity 14.01: Requesting Data from a Web Server and Processing the Response
      2. Activity 14.02: Sending Data to a Web Server and Checking Whether the Data Was Received Using POST and GET
    15. 15. HTTP Servers
      1. Activity 15.01: Adding a Page Counter to an HTML Page
      2. Activity 15.02: Serving a Request with a JSON Payload
      3. Activity 15.03: External Template
    16. 16. Concurrent Work
      1. Activity 16.01: Listing Numbers
      2. Activity 16.02: Source Files
    17. 17. Using Go Tools
      1. Activity 17.01: Using gofmt, goimport, go vet, and go get to Correct a File
    18. 18. Security
      1. Activity 18.01: Authenticating Users on the Application Using Hashed Passwords
      2. Activity 18.02: Creating CA Signed Certificates Using Crypto Libraries
    19. 19. Special Features
      1. Activity 19.01: Defining Build Constraints Using Filenames
      2. Activity 19.02: Using Wildcard with Go Test
    20. What Next?
      1. The SQL Workshop
        1. The Java Workshop
        2. The Kubernetes Workshop
        3. Please leave a review

Product information

  • Title: The Go Workshop
  • Author(s): Delio D'Anna, Andrew Hayes, Sam Hennessy, Jeremy Leasor, Gobin Sougrakpam, Dániel Szabó
  • Release date: December 2019
  • Publisher(s): Packt Publishing
  • ISBN: 9781838647940