O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Mastering Go

Book Description

Exploring the major features and packages of Go, along with its types and data-structures, enabling the reader to write threadsafe, concurrent cloud, and network applications

About This Book
  • Not your typical introduction to the Golang programming language
  • Exploring Golang cradle to grave, completes the developer's Golang education
  • A thorough exploration into the core libraries and Golang features, that usually are taken for granted
  • In depth explanation, detailing the rationale behind composite data types, Golang concurrency, and the Golang networking library
Who This Book Is For

This book is for Golang programmers. You should have previously read an introductory book on Go, or to have worked through the Tour of Go or an equivalent online course. This book will definitely help to remember the basic concepts of concurrency, but network programming will be explained. A certain amount of previous coding and production experience would be helpful.

What You Will Learn
  • Understand the design choices of Golang syntax
  • Know enough Go internals to be able to optimize Golang code
  • Appreciate concurrency models available in Golang
  • Understand the interplay of systems and networking code
  • Write server-level code that plays well in all environments
  • Understand the context and appropriate use of Go data types and data structures
In Detail

The Go programming language, often referred to as Golang (albeit wrongly), is really making strides, with some masterclass developments, architected by the greatest programming minds. Tobias Lutke, CEO of Shopify, recently quoted as saying “Go will be the server language of the future”, powerful words, with much ambition. Go programmers are in high demand, but more controversially, Go takes the stage, where C and Unix programmers previously led the way.

The growth of the Go language has seen it become the means by which systems, networking, web, and cloud applications are implemented. Comfortable with syntax, you'll benefit by mastering the use of the libraries and utilise its features, speed, and efficiency, for which the Go ecology is justly famous.

You already know a little Go syntax and you've written some small projects, most Go programmers face the difficulty of having to integrate their Golang skills with production code. Typical introductions to Go programming, often stop short of this transition, the author continue on, showing you just how to tackle this.

Offering a compendium of Go, the book begins with an account of how Go has been implemented, also, the reader will benefit from a dedicated chapter, an in-depth account of concurrency, systems and network programming, imperative for modern-day native cloud development.

Style and approach

The approach is a practical one, very much hands-on, and a bit more demanding and in-depth than your average programming language introduction. The aim is to enable a Golang programmer to write and put in production a complete Golang application, regardless of the environment, which will be achieved by a masterclass of well- formed exercises.

Downloading the example code for this book You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Table of Contents

  1. Title Page
  2. Copyright and Credits
    1. Mastering Go
  3. Packt Upsell
    1. Why subscribe?
    2. PacktPub.com
  4. Contributors
    1. About the author
    2. About the reviewer
    3. Packt is searching for authors like you
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
      1. Download the example code files
      2. Download the color images
      3. Conventions used
    4. Get in touch
      1. Reviews
  6. Go and the Operating System
    1. The structure of the book
    2. The history of Go
    3. Why learn Go?
    4. Go advantages
      1. Is Go perfect?
        1. What is a preprocessor?
      2. The godoc utility
    5. Compiling Go code
    6. Executing Go code
    7. Two Go rules
      1. You either use a Go package or do not include it
      2. There is only one way to format curly braces
    8. Downloading Go packages
    9. Unix stdin, stdout, and stderr
    10. About printing output
    11. Using standard output
    12. Getting user input
    13. About := and =
      1. Reading from standard input
      2. Working with command-line arguments
    14. About error output
    15. Writing to log files
      1. Logging levels
      2. Logging facilities
      3. Log servers
      4. A Go program that sends information to log files
      5. About log.Fatal()
      6. About log.Panic()
    16. Error handling in Go
      1. The error data type
      2. Error handling
    17. Additional resources
    18. Exercises
    19. Summary
  7. Understanding Go Internals
    1. The Go compiler
    2. Garbage Collection
      1. The Tricolor algorithm
      2. More about the operation of the Go Garbage Collector
      3. Unsafe code
      4. About the unsafe package
      5. Another example of the unsafe package
    3. Calling C code from Go
      1. Calling C code from Go using the same file
      2. Calling C code from Go using separate files
      3. The C code
      4. The Go code
      5. Mixing Go and C code
    4. Calling Go functions from C code
      1. The Go package
      2. The C code
    5. The defer keyword
    6. Panic and Recover
      1. Using the panic function on its own
    7. Two handy Unix utilities
      1. The strace tool
      2. The dtrace tool
    8. Your Go environment
    9. The Go Assembler
    10. Node Trees
    11. Learning more about go build
    12. General Go coding advices
    13. Additional Resources
    14. Exercises
    15. Summary
  8. Working with Basic Go Data Types
    1. Go loops
      1. The for loop
      2. The while loop
      3. The range keyword
      4. Examples of Go for loops
    2. Go arrays
      1. Multi-dimensional arrays
      2. The shortcomings of Go arrays
    3. Go slices
      1. Performing basic operations on slices
      2. Slices are being expanded automatically
      3. Byte slices
      4. The copy() function
      5. Multidimensional slices
      6. Another example of slices
      7. Sorting slices using sort.slice()
    4. Go maps
      1. Storing to a nil map
      2. When you should use a map?
    5. Go constants
      1. The constant generator iota
    6. Go pointers
    7. Dealing with times and dates
      1. Working with times
      2. Parsing times
      3. Working with dates
      4. Parsing dates
      5. Changing date and time formats
    8. Additional resources
    9. Exercises
    10. Summary
  9. The Uses of Composite Types
    1. About composite types
    2. Structures
      1. Pointers to structures
      2. Using the new keyword
    3. Tuples
    4. Regular expressions and pattern matching
      1. Now for some theory
      2. A simple example
      3. A more advanced example
      4. Matching IPv4 addresses
    5. Strings
      1. What is a rune?
      2. The Unicode package
      3. The strings package
    6. The switch statement
    7. Calculating Pi with great accuracy
    8. Developing a key/value store in Go
    9. Additional resources
    10. Exercises
    11. Summary
  10. Enhancing Go Code with Data Structures
    1. About graphs and nodes
    2. Algorithm complexity
    3. Binary trees in Go
      1. Implementing a binary tree in Go
      2. Advantages of binary trees
    4. Hash tables in Go
      1. Implementing a hash table in Go
      2. Implementing the lookup functionality
      3. Advantages of hash tables
    5. Linked lists in Go
      1. Implementing a linked list in Go
      2. Advantages of linked lists
    6. Doubly linked lists in Go
      1. Implementing a doubly linked list in Go
      2. Advantages of doubly linked lists
    7. Queues in Go
      1. Implementing a queue in Go
    8. Stacks in Go
      1. Implementing a stack in Go
    9. The container package
      1. Using container/heap
      2. Using container/list
      3. Using container/ring
    10. Generating random numbers
      1. Generating random strings
    11. Additional Resources
    12. Exercises
    13. Summary
  11. What You Might Not Know About Go Packages
    1. About Go packages
    2. About Go functions
      1. Anonymous functions
      2. Functions that return multiple values
      3. The return values of a function can be named!
      4. Functions with pointer parameters
      5. Functions that return pointers
      6. Functions that return other functions
      7. Functions that accept other functions as parameters
    3. Developing your own Go packages
      1. Compiling a Go package
      2. Private variables and functions
      3. The init() function
    4. Reading the Go code of a standard Go package
      1. Exploring the code of the net/url package
      2. Looking at the Go code of the log/syslog package
    5. Creating good Go packages
    6. The syscall package
      1. Finding out how fmt.Println() really works
    7. Text and HTML templates
      1. Generating text output
      2. Constructing HTML output
      3. Basic SQLite3 commands
    8. Additional resources
    9. Exercises
    10. Summary
  12. Reflection and Interfaces for All Seasons
    1. Type methods
    2. Go interfaces
    3. About type assertion
    4. Developing your own interfaces
      1. Using a Go interface
      2. Using switch with interface and data types
    5. Reflection
      1. A simple Reflection example
      2. A more advanced reflection example
      3. The three disadvantages of reflection
    6. Object-oriented programming in Go!
    7. Additional resources
    8. Exercises
    9. Summary
  13. Telling a Unix System What to Do
    1. About Unix processes
    2. The flag package
    3. The io.Reader and io.Writer interfaces
      1. Buffered and unbuffered file input and output
    4. The bufio package
    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
    6. Reading the amount of data you want from a file
    7. Why are we using binary format?
    8. Reading CSV files
    9. Writing to a file
    10. Loading and saving data on disk
    11. The strings package revisited
    12. About the bytes package
    13. File permissions
    14. Handling Unix signals
      1. Handling two signals
      2. Handling all signals
    15. Programming Unix pipes in Go
      1. Implementing the cat(1) utility in Go
    16. Traversing directory trees
    17. Using eBPF from Go
    18. About syscall.PtraceRegs
    19. Tracing system calls
    20. User ID and group ID
    21. Additional resources
    22. Exercises
    23. Summary
  14. Go Concurrency – Goroutines, Channels, and Pipelines
    1. About processes, threads, and goroutines
      1. The Go scheduler
      2. Concurrency and parallelism
    2. Goroutines
      1. Creating a goroutine
      2. Creating multiple goroutines
    3. Waiting for your goroutines to finish
      1. What if the number of Add() and Done() calls do not agree?
    4. Channels
      1. Writing to a channel
      2. Reading from a channel
      3. Channels as function parameters
    5. Pipelines
    6. Additional resources
    7. Exercises
    8. Summary
  15. Go Concurrency – Advanced Topics
    1. The Go scheduler revisited
      1. The GOMAXPROCS environment variable
    2. The select keyword
    3. Timing out a goroutine
      1. Timing out a goroutine – take 1
      2. Timing out a goroutine – take 2
    4. Go channels revisited
      1. Signal channels
      2. Buffered channels
      3. Nil channels
      4. Channel of channels
      5. Specifying the order of execution for your goroutines
    5. 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. Sharing memory using goroutines
    6. Catching race conditions
    7. The context package
      1. An advanced example of the context package
      2. Worker pools
    8. Additional resources
    9. Exercises
    10. Summary
  16. Code Testing, Optimization, and Profiling
    1. The Go version used in this chapter
      1. Comparing Go version 1.10 with Go version 1.9
    2. Installing a beta or RC version of Go
    3. About optimization
    4. Optimizing Go code
    5. Profiling Go code
      1. The net/http/pprof standard Go package
      2. A simple profiling example
      3. A convenient external package for profiling
      4. The web interface of the Go profiler
        1. A profiling example that uses the web interface
        2. A quick introduction to Graphviz
    6. The go tool trace utility
    7. Testing Go code
      1. Writing tests for existing Go code
    8. Benchmarking Go code
    9. A simple benchmarking example
      1. A wrong benchmark function
    10. Benchmarking buffered writing
    11. Finding unreachable Go code
    12. Cross-compilation
    13. Creating example functions
    14. Generating documentation
    15. Additional resources
    16. Exercises
    17. Summary
  17. The Foundations of Network Programming in Go
    1. About net/http, net, and http.RoundTripper
      1. The http.Response type
      2. The http.Request type
      3. The http.Transport type
    2. About TCP/IP
    3. About IPv4 and IPv6
    4. The nc(1) command-line utility
    5. Reading the configuration of network interfaces
    6. Performing DNS lookups
      1. Getting the NS records of a domain
      2. Getting the MX records of a domain
    7. Creating a web server in Go
      1. Profiling an HTTP server
      2. Creating a website in Go
    8. HTTP tracing
      1. Testing HTTP handlers
    9. Creating a web client in Go
      1. Making your Go web client more advanced
    10. Timing out HTTP connections
      1. More information about SetDeadline
      2. Setting the timeout period on the server side
      3. Yet another way to time out!
    11. Wireshark and tshark tools
    12. Additional resources
    13. Exercises
    14. Summary
  18. Network Programming – Building Servers and Clients
    1. The net standard Go package
    2. A TCP client
      1. A slightly different version of the TCP client
    3. A TCP server
      1. A slightly different version of the TCP server
    4. A UDP client
    5. Developing a UDP server
    6. A concurrent TCP server
      1. A handy concurrent TCP server
    7. Remote Procedure Call (RPC)
      1. The RPC client
      2. The RPC server
    8. Doing low-level network programming
      1. Grabbing raw ICMP network data
    9. Where to go next?
    10. Additional resources
    11. Exercises
    12. Summary
  19. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think