Mastering Go - Third Edition

Book description

Master key features of Go, including advanced concepts like concurrency and working with JSON, to create and optimize real-world services, network servers, and clients

Key Features

  • This third edition of the bestselling guide to advanced Go programming has been overhauled and expanded to cover RESTful servers, the WebSocket protocol, and Go generics
  • Use real-world exercises to build high-performance network servers and powerful command line utilities
  • Packed with practical examples and utilities to apply to your own development work and administrative tasks
  • Get clear explanations about Go nuances and features to simplify Go development

Book Description

Mastering Go is the essential guide to putting Go to work on real production systems. This freshly updated third edition includes topics like creating RESTful servers and clients, understanding Go generics, and developing gRPC servers and clients.

Mastering Go was written for programmers who want to explore the capabilities of Go in practice. As you work your way through the chapters, you'll gain confidence and a deep understanding of advanced Go concepts, including concurrency and the operation of the Go Garbage Collector, using Go with Docker, writing powerful command-line utilities, working with JavaScript Object Notation (JSON) data, and interacting with databases. You'll also improve your understanding of Go internals to optimize Go code and use data types and data structures in new and unexpected ways.

This essential Go programming book will also take you through the nuances and idioms of Go with exercises and resources to fully embed your newly acquired knowledge.

With the help of Mastering Go, you'll become an expert Go programmer by building Go systems and implementing advanced Go techniques in your projects.

What you will learn

  • Use Go in production
  • Write reliable, high-performance concurrent code
  • Manipulate data structures including slices, arrays, maps, and pointers
  • Develop reusable packages with reflection and interfaces
  • Become familiar with generics for effective Go programming
  • Create concurrent RESTful servers, and build gRPC clients and servers
  • Define Go structures for working with JSON data

Who this book is for

You'll need to know the basics of Go before you get started with this book, but beyond that, anyone can sink their teeth into it. It's written primarily for Go programmers who have a bit of experience with the language and want to become expert practitioners.

Table of contents

  1. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Get in touch
  2. A Quick Introduction to Go
    1. Introducing Go
      1. The history of Go
      2. Why UNIX and not Windows?
      3. The advantages of Go
      4. The go doc and godoc utilities
    2. Hello World!
      1. Introducing functions
      2. Introducing packages
    3. Running Go code
      1. Compiling Go code
      2. Using Go like a scripting language
      3. Important formatting and coding rules
    4. Important characteristics of Go
      1. Defining and using variables
        1. Printing variables
      2. Controlling program flow
      3. Iterating with for loops and range
      4. Getting user input
        1. Reading from standard input
        2. Working with command-line arguments
      5. Using error variables to differentiate between input types
      6. Understanding the Go concurrency model
    5. Developing the which(1) utility in Go
    6. Logging information
      1. log.Fatal() and log.Panic()
      2. Writing to a custom log file
      3. Printing line numbers in log entries
    7. Overview of Go generics
    8. Developing a basic phone book application
    9. Exercises
    10. Summary
    11. Additional resources
  3. Basic Go Data Types
    1. The error data type
    2. Numeric data types
    3. Non-numeric data types
      1. Strings, Characters, and Runes
        1. Converting from int to string
        2. The unicode package
        3. The strings package
      2. Times and dates
        1. A utility for parsing dates and times
        2. Working with different time zones
    4. Go constants
      1. The constant generator iota
    5. Grouping similar data
      1. Arrays
      2. Slices
        1. About slice length and capacity
        2. Selecting a part of a slice
        3. Byte slices
        4. Deleting an element from a slice
        5. How slices are connected to arrays
        6. The copy() function
        7. Sorting slices
    6. Pointers
    7. Generating random numbers
      1. Generating random strings
      2. Generating secure random numbers
    8. Updating the phone book application
    9. Exercises
    10. Summary
    11. Additional resources
  4. Composite Data Types
    1. Maps
      1. Storing to a nil map
      2. Iterating over maps
    2. Structures
      1. Defining new structures
      2. Using the new keyword
      3. Slices of structures
    3. Regular expressions and pattern matching
      1. About Go regular expressions
      2. Matching names and surnames
      3. Matching integers
      4. Matching the fields of a record
    4. Improving the phone book application
      1. Working with CSV files
      2. Adding an index
      3. The improved version of the phone book application
    5. Exercises
    6. Summary
    7. Additional resources
  5. Reflection and Interfaces
    1. Reflection
      1. Learning the internal structure of a Go structure
      2. Changing structure values using reflection
      3. The three disadvantages of reflection
    2. Type methods
      1. Creating type methods
      2. Using type methods
    3. Interfaces
      1. The sort.Interface interface
      2. The empty interface
      3. Type assertions and type switches
      4. The map[string]interface{} map
      5. The error data type
      6. Writing your own interfaces
        1. Using a Go interface
        2. Implementing sort.Interface for 3D shapes
    4. Working with two different CSV file formats
    5. Object-oriented programming in Go
    6. Updating the phone book application
      1. Setting up the value of the CSV file
      2. Using the sort package
    7. Exercises
    8. Summary
    9. Additional resources
  6. Go Packages and Functions
    1. Go packages
      1. Downloading Go packages
    2. Functions
      1. Anonymous functions
      2. Functions that return multiple values
      3. The return values of a function can be named
      4. Functions that accept other functions as parameters
      5. Functions can return other functions
      6. Variadic functions
      7. The defer keyword
    3. Developing your own packages
      1. The init() function
      2. Order of execution
    4. Using GitHub to store Go packages
    5. A package for working with a database
      1. Getting to know your database
      2. Storing the Go package
      3. The design of the Go package
      4. The implementation of the Go package
      5. Testing the Go package
    6. Modules
    7. Creating better packages
    8. Generating documentation
    9. GitLab Runners and Go
      1. The initial version of the configuration file
      2. The final version of the configuration file
    10. GitHub Actions and Go
      1. Storing secrets in GitHub
      2. The final version of the configuration file
    11. Versioning utilities
    12. Exercises
    13. Summary
    14. Additional resources
  7. Telling a UNIX System What to Do
    1. stdin, stdout, and stderr
    2. UNIX processes
    3. Handling UNIX signals
      1. Handling two signals
    4. File I/O
      1. The io.Reader and io.Writer interfaces
      2. Using and misusing io.Reader and io.Writer
      3. Buffered and unbuffered file I/O
    5. Reading text files
      1. Reading a text file line by line
      2. Reading a text file word by word
      3. Reading a text file character by character
      4. Reading from /dev/random
      5. Reading a specific amount of data from a file
    6. Writing to a file
    7. Working with JSON
      1. Using Marshal() and Unmarshal()
      2. Structures and JSON
      3. Reading and writing JSON data as streams
      4. Pretty printing JSON records
    8. Working with XML
      1. Converting JSON to XML and vice versa
    9. Working with YAML
    10. The viper package
      1. Using command-line flags
      2. Reading JSON configuration files
    11. The cobra package
      1. A utility with three commands
      2. Adding command-line flags
      3. Creating command aliases
      4. Creating subcommands
    12. Finding cycles in a UNIX file system
    13. New to Go 1.16
      1. Embedding files
      2. ReadDir and DirEntry
      3. The io/fs package
    14. Updating the phone book application
      1. Using cobra
      2. Storing and loading JSON data
      3. Implementing the delete command
      4. Implementing the insert command
      5. Implementing the list command
      6. Implementing the search command
    15. Exercises
    16. Summary
    17. Additional resources
  8. Go Concurrency
    1. Processes, threads, and goroutines
    2. The Go scheduler
      1. The GOMAXPROCS environment variable
      2. Concurrency and parallelism
    3. Goroutines
      1. Creating a goroutine
      2. Creating multiple goroutines
      3. Waiting for your goroutines to finish
      4. What if the number of Add() and Done() calls differ?
      5. Creating multiple files with goroutines
    4. Channels
      1. Writing to and reading from a channel
      2. Receiving from a closed channel
      3. Channels as function parameters
    5. Race conditions
      1. The Go race detector
    6. The select keyword
    7. Timing out a goroutine
      1. Timing out a goroutine – inside main()
      2. Timing out a goroutine – outside main()
    8. Go channels revisited
      1. Buffered channels
      2. nil channels
      3. Worker pools
      4. Signal channels
        1. Specifying the order of execution for your goroutines
    9. Shared memory and shared variables
      1. The sync.Mutex type
        1. What happens if you forget to unlock a mutex?
      2. The sync.RWMutex type
      3. The atomic package
      4. Sharing memory using goroutines
    10. Closured variables and the go statement
    11. The context package
      1. Using context as a key/value store
    12. The semaphore package
    13. Exercises
    14. Summary
    15. Additional resources
  9. Building Web Services
    1. The net/http package
      1. The http.Response type
      2. The http.Request type
      3. The http.Transport type
    2. Creating a web server
    3. Updating the phone book application
      1. Defining the API
      2. Implementing the handlers
    4. Exposing metrics to Prometheus
      1. The runtime/metrics package
      2. Exposing metrics
        1. Creating a Docker image for a Go server
        2. Exposing the desired metrics
      3. Reading metrics
      4. Putting the metrics in Prometheus
      5. Visualizing Prometheus metrics in Grafana
    5. Developing web clients
      1. Using http.NewRequest() to improve the client
      2. Creating a client for the phone book service
    6. Creating file servers
      1. Downloading the contents of the phone book application
    7. Timing out HTTP connections
      1. Using SetDeadline()
      2. Setting the timeout period on the client side
      3. Setting the timeout period on the server side
    8. Exercises
    9. Summary
    10. Additional resources
  10. Working with TCP/IP and WebSocket
    1. TCP/IP
      1. The nc(1) command-line utility
    2. The net package
    3. Developing a TCP client
      1. Developing a TCP client with net.Dial()
      2. Developing a TCP client that uses net.DialTCP()
    4. Developing a TCP server
      1. Developing a TCP server with net.Listen()
      2. Developing a TCP server that uses net.ListenTCP()
    5. Developing a UDP client
    6. Developing a UDP server
    7. Developing concurrent TCP servers
    8. Working with UNIX domain sockets
      1. A UNIX domain socket server
      2. A UNIX domain socket client
    9. Creating a WebSocket server
      1. The implementation of the server
        1. Using websocat
        2. Using JavaScript
    10. Creating a WebSocket client
    11. Exercises
    12. Summary
    13. Additional resources
  11. Working with REST APIs
    1. An introduction to REST
    2. Developing RESTful servers and clients
      1. A RESTful server
      2. A RESTful client
    3. Creating a functional RESTful server
      1. The REST API
      2. Using gorilla/mux
      3. The use of subrouters
      4. Working with the database
      5. Testing the restdb package
      6. Implementing the RESTful server
      7. Testing the RESTful server
        1. Testing GET handlers
        2. Testing POST handlers
        3. Testing the PUT handler
        4. Testing the DELETE handler
    4. Creating a RESTful client
      1. Creating the structure of the command-line client
      2. Implementing the RESTful client commands
      3. Using the RESTful client
      4. Working with multiple REST API versions
    5. Uploading and downloading binary files
    6. Using Swagger for REST API documentation
      1. Documenting the REST API
      2. Generating the documentation file
      3. Serving the documentation file
    7. Exercises
    8. Summary
    9. Additional resources
  12. Code Testing and Profiling
    1. Optimizing code
    2. Benchmarking code
      1. Rewriting the main() function for better testing
      2. Benchmarking buffered writing and reading
      3. The benchstat utility
      4. Wrongly defined benchmark functions
    3. Profiling code
      1. Profiling a command-line application
      2. Profiling an HTTP server
      3. The web interface of the Go profiler
    4. The go tool trace utility
      1. Tracing a web server from a client
      2. Visiting all routes of a web server
    5. Testing Go code
      1. Writing tests for ./ch03/intRE.go
      2. The TempDir function
      3. The Cleanup() function
      4. The testing/quick package
      5. Timing out tests
      6. Testing code coverage
      7. Finding unreachable Go code
    6. Testing an HTTP server with a database backend
    7. Fuzzing
    8. Cross-compilation
    9. Using go:generate
    10. Creating example functions
    11. Exercises
    12. Summary
    13. Additional resources
  13. Working with gRPC
    1. Introduction to gRPC
      1. Protocol buffers
    2. Defining an interface definition language file
    3. Developing a gRPC server
    4. Developing a gRPC client
      1. Testing the gRPC server with the client
    5. Exercises
    6. Summary
    7. Additional resources
  14. Go Generics
    1. Introducing generics
    2. Constraints
      1. Creating constraints
    3. Defining new data types with generics
      1. Using generics in Go structures
    4. Interfaces versus generics
    5. Reflection versus generics
    6. Exercises
    7. Summary
    8. Additional resources
  15. Appendix A – Go Garbage Collector
    1. Heap and stack
    2. Garbage collection
      1. The tricolor algorithm
      2. More about the operation of the Go garbage collector
      3. Maps, slices, and the Go garbage collector
        1. Using a slice
        2. Using a map with pointers
        3. Using a map without pointers
        4. Splitting the map
      4. Comparing the performance of the presented techniques
    3. Additional resources
  16. Other Books You May Enjoy
  17. Index

Product information

  • Title: Mastering Go - Third Edition
  • Author(s): Mihalis Tsoukalos
  • Release date: August 2021
  • Publisher(s): Packt Publishing
  • ISBN: 9781801079310