Book Image

Go Programming Cookbook - Second Edition

By : Aaron Torres
Book Image

Go Programming Cookbook - Second Edition

By: Aaron Torres

Overview of this book

Go (or Golang) is a statically typed programming language developed at Google. Known for its vast standard library, it also provides features such as garbage collection, type safety, dynamic-typing capabilities, and additional built-in types. This book will serve as a reference while implementing Go features to build your own applications. This Go cookbook helps you put into practice the advanced concepts and libraries that Golang offers. The recipes in the book follow best practices such as documentation, testing, and vendoring with Go modules, as well as performing clean abstractions using interfaces. You'll learn how code works and the common pitfalls to watch out for. The book covers basic type and error handling, and then moves on to explore applications, such as websites, command-line tools, and filesystems, that interact with users. You'll even get to grips with parallelism, distributed systems, and performance tuning. By the end of the book, you'll be able to use open source code and concepts in Go programming to build enterprise-class applications without any hassle.
Table of Contents (16 chapters)

Using structures and closures for stateful handlers

Due to the sparse signatures of HTTP handler functions, it may seem tricky to add state to a handler. For example, there are a variety of ways to include a database connection. Two approaches to doing this are to pass in the state via closures, which is useful for achieving flexibility on a single handler, or by using a structure.

This recipe will demonstrate both. We'll use a struct controller to store a storage interface and create two routes with a single handler that are modified by an outer function.

How to do it...

The following steps cover the writing and running of your application:

  1. From your Terminal or console application,createa new directory called~/projects/go-programming-cookbook/chapter8/controllers, and navigate to this directory.
  2. Run the following command:
          $ go mod init github.com/PacktPublishing/Go-Programming-Cookbook-Second...