Book Image

.Go Programming Blueprints - Second Edition

By : Mat Ryer
Book Image

.Go Programming Blueprints - Second Edition

By: Mat Ryer

Overview of this book

Go is the language of the Internet age, and the latest version of Go comes with major architectural changes. Implementation of the language, runtime, and libraries has changed significantly. The compiler and runtime are now written entirely in Go. The garbage collector is now concurrent and provides dramatically lower pause times by running in parallel with other Go routines when possible. This book will show you how to leverage all the latest features and much more. This book shows you how to build powerful systems and drops you into real-world situations. You will learn to develop high quality command-line tools that utilize the powerful shell capabilities and perform well using Go's in-built concurrency mechanisms. Scale, performance, and high availability lie at the heart of our projects, and the lessons learned throughout this book will arm you with everything you need to build world-class solutions. You will get a feel for app deployment using Docker and Google App Engine. Each project could form the basis of a start-up, which means they are directly applicable to modern software markets.
Table of Contents (19 chapters)
Go Programming Blueprints Second Edition
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
Preface

Injecting dependencies


Now that we can be sure that a request has a valid API key and is CORS-compliant, we must consider how handlers will connect to the database. One option is to have each handler dial its own connection, but this isn't very DRY (Don't Repeat Yourself) and leaves room for potentially erroneous code, such as code that forgets to close a database session once it is finished with it. It also means that if we wanted to change how we connected to the database (perhaps we want to use a domain name instead of a hardcoded IP address), we might have to modify our code in many places, rather than one.

Instead, we will create a new type that encapsulates all the dependencies for our handlers and construct it with a database connection in main.go.

Create a new type called Server:

// Server is the API server. 
type Server struct { 
  db *mgo.Session 
} 

Our handler functions will be methods of this server, which is how they will be able to access the database session.