Go Programming Blueprints
By Mat Ryer
()
About this ebook
- Learn to apply the nuances of the Go language, and get to know the open source community that surrounds it to implement a wide range of start-up quality projects
- Write interesting, and clever but simple code, and learn skills and techniques that are directly transferrable to your own projects
- Discover how to write code capable of delivering massive world-class scale performance and availability
Intended for seasoned Go programmers who want to put their expertise in Go to use to solve big, real-world, modern problems. With a basic understanding of channels and goroutines, you will hone your skills to build tools and programs that are quick and simple. You need not be an expert in distributed systems or technologies in order to deliver solutions capable of great scale. It is assumed that you are familiar with the basic concepts of Go.
Read more from Mat Ryer
Test-Driven Development in Go: A practical guide to writing idiomatic and efficient Go tests through real-world examples Rating: 0 out of 5 stars0 ratingsGo Programming Blueprints - Second Edition Rating: 4 out of 5 stars4/5Go: Building Web Applications Rating: 0 out of 5 stars0 ratings
Related to Go Programming Blueprints
Related ebooks
The Way to Go: A Thorough Introduction to the Go Programming Language Rating: 2 out of 5 stars2/5Git Best Practices Guide Rating: 0 out of 5 stars0 ratingsNode Web Development, Second Edition Rating: 0 out of 5 stars0 ratingsDeploying Node.js Rating: 5 out of 5 stars5/5Go in Practice Rating: 5 out of 5 stars5/5Go in Action Rating: 5 out of 5 stars5/5Go Programming Blueprints - Second Edition Rating: 5 out of 5 stars5/5Go Cookbook Rating: 5 out of 5 stars5/5Go Design Patterns Rating: 5 out of 5 stars5/5Go Web Programming Rating: 5 out of 5 stars5/5Bootstrapping Microservices with Docker, Kubernetes, and Terraform: A project-based guide Rating: 3 out of 5 stars3/5Rust in Action Rating: 4 out of 5 stars4/5The Go Workshop: Learn to write clean, efficient code and build high-performance applications with Go Rating: 0 out of 5 stars0 ratingsKnative in Action Rating: 0 out of 5 stars0 ratingsLearning Go Programming: Build ScalableNext-Gen Web Application using Golang (English Edition) Rating: 0 out of 5 stars0 ratingsGetting MEAN with Mongo, Express, Angular, and Node Rating: 5 out of 5 stars5/5HTTP/2 in Action Rating: 0 out of 5 stars0 ratingsAPI Design Patterns Rating: 5 out of 5 stars5/5Tanmay Teaches Go: The Ideal Language for Backend Developers Rating: 0 out of 5 stars0 ratingsReal-World Functional Programming: With examples in F# and C# Rating: 0 out of 5 stars0 ratingsWebAssembly in Action: With examples using C++ and Emscripten Rating: 0 out of 5 stars0 ratingsGet Programming with Go Rating: 0 out of 5 stars0 ratingsFive Lines of Code: How and when to refactor Rating: 0 out of 5 stars0 ratingsLearning Go Programming Rating: 5 out of 5 stars5/5Kafka in Action Rating: 0 out of 5 stars0 ratingsElectron in Action Rating: 0 out of 5 stars0 ratingsOAuth 2 in Action Rating: 0 out of 5 stars0 ratingsThe Design of Web APIs Rating: 0 out of 5 stars0 ratings
Internet & Web For You
Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Coding For Dummies Rating: 5 out of 5 stars5/5Social Engineering: The Science of Human Hacking Rating: 3 out of 5 stars3/5No Place to Hide: Edward Snowden, the NSA, and the U.S. Surveillance State Rating: 4 out of 5 stars4/5HTML in 30 Pages Rating: 5 out of 5 stars5/5The Gothic Novel Collection Rating: 5 out of 5 stars5/5How to Be Invisible: Protect Your Home, Your Children, Your Assets, and Your Life Rating: 4 out of 5 stars4/5The Hacker Crackdown: Law and Disorder on the Electronic Frontier Rating: 4 out of 5 stars4/5The $1,000,000 Web Designer Guide: A Practical Guide for Wealth and Freedom as an Online Freelancer Rating: 4 out of 5 stars4/5Six Figure Blogging Blueprint Rating: 5 out of 5 stars5/5How to Disappear and Live Off the Grid: A CIA Insider's Guide Rating: 0 out of 5 stars0 ratingsEverybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5How To Start A Profitable Authority Blog In Under One Hour Rating: 5 out of 5 stars5/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsSurveillance and Surveillance Detection: A CIA Insider's Guide Rating: 3 out of 5 stars3/5Podcasting For Dummies Rating: 4 out of 5 stars4/5The Beginner's Affiliate Marketing Blueprint Rating: 4 out of 5 stars4/5Notion for Beginners: Notion for Work, Play, and Productivity Rating: 4 out of 5 stars4/5Cybersecurity All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsPython: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Coding with AI For Dummies Rating: 0 out of 5 stars0 ratingsWireless Hacking 101 Rating: 5 out of 5 stars5/5Content Chemistry: The Illustrated Handbook for Content Marketing Rating: 5 out of 5 stars5/5200+ Ways to Protect Your Privacy: Simple Ways to Prevent Hacks and Protect Your Privacy--On and Offline Rating: 0 out of 5 stars0 ratingsTor and the Dark Art of Anonymity Rating: 5 out of 5 stars5/5Beginner's Guide To Starting An Etsy Print-On-Demand Shop Rating: 0 out of 5 stars0 ratings
Reviews for Go Programming Blueprints
0 ratings0 reviews
Book preview
Go Programming Blueprints - Mat Ryer
Table of Contents
Go Programming Blueprints
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Chat Application with Web Sockets
A simple web server
Templates
Doing things once
Using your own handlers
Properly building and executing Go programs
Modeling a chat room and clients on the server
Modeling the client
Modeling a room
Concurrency programming using idiomatic Go
Turning a room into an HTTP handler
Use helper functions to remove complexity
Creating and using rooms
Building an HTML and JavaScript chat client
Getting more out of templates
Tracing code to get a look under the hood
Writing a package using TDD
Interfaces
Unit tests
Red-green testing
Implementing the interface
Unexported types being returned to users
Using our new trace package
Making tracing optional
Clean package APIs
Summary
2. Adding Authentication
Handlers all the way down
Making a pretty social sign-in page
Endpoints with dynamic paths
OAuth2
Open source OAuth2 packages
Tell the authentication providers about your app
Implementing external logging in
Logging in
Handling the response from the provider
Presenting the user data
Augmenting messages with additional data
Summary
3. Three Ways to Implement Profile Pictures
Avatars from the authentication server
Getting the avatar URL
Transmitting the avatar URL
Adding the avatar to the user interface
Logging out
Making things prettier
Implementing Gravatar
Abstracting the avatar URL process
The authentication service and avatar's implementation
Using an implementation
Gravatar implementation
Uploading an avatar picture
User identification
An upload form
Handling the upload
Serving the images
The Avatar implementation for local files
Supporting different file types
Refactoring and optimizing our code
Replacing concrete types with interfaces
Changing interfaces in a test-driven way
Fixing existing implementations
Global variables versus fields
Implementing our new design
Tidying up and testing
Combining all three implementations
Summary
4. Command-line Tools to Find Domain Names
Pipe design for command-line tools
Five simple programs
Sprinkle
Exercise – configurable transformations
Domainify
Exercise – making top-level domains configurable
Coolify
Synonyms
Using environment variables for configuration
Consuming a web API
Getting domain suggestions
Available
Composing all five programs
One program to rule them all
Summary
5. Building Distributed Systems and Working with Flexible Data
System design
Database design
Installing the environment
NSQ
NSQ driver for Go
MongoDB
MongoDB driver for Go
Starting the environment
Votes from Twitter
Authorization with Twitter
Extracting the connection
Reading environment variables
Reading from MongoDB
Reading from Twitter
Signal channels
Publishing to NSQ
Gracefully starting and stopping
Testing
Counting votes
Connecting to the database
Consuming messages in NSQ
Keeping the database updated
Responding to Ctrl + C
Running our solution
Summary
6. Exposing Data and Functionality through a RESTful Data Web Service API
RESTful API design
Sharing data between handlers
Wrapping handler functions
API key
Database session
Per request variables
Cross-browser resource sharing
Responding
Understanding the request
A simple main function to serve our API
Using handler function wrappers
Handling endpoints
Using tags to add metadata to structs
Many operations with a single handler
Reading polls
Creating a poll
Deleting a poll
CORS support
Testing our API using curl
A web client that consumes the API
An index page showing a list of polls
A page to create a new poll
A page to show details of the poll
Running the solution
Summary
7. Random Recommendations Web Service
Project overview
Project design specifics
Representing data in code
Public views of Go structs
Generating random recommendations
Google Places API key
Enumerators in Go
Test-driven enumerator
Querying the Google Places API
Building recommendations
Handlers that use query parameters
CORS
Testing our API
Web application
Summary
8. Filesystem Backup
Solution design
Project structure
Backup package
Obvious interfaces?
Implementing ZIP
Has the filesystem changed?
Checking for changes and initiating a backup
Hardcoding is OK for a short while
The user command-line tool
Persisting small data
Parsing arguments
Listing the paths
String representations for your own types
Adding paths
Removing paths
Using our new tool
The daemon backup tool
Duplicated structures
Caching data
Infinite loops
Updating filedb records
Testing our solution
Summary
A. Good Practices for a Stable Go Environment
Installing Go
Installing the C tools
Downloading and building Go from the source
Configuring Go
Getting GOPATH right
Go tools
Cleaning up, building, and running tests on save
Sublime Text 3
Summary
Index
Go Programming Blueprints
Go Programming Blueprints
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors, will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: January 2015
Production reference: 1200115
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-802-0
www.packtpub.com
Credits
Author
Mat Ryer
Reviewers
Tyler Bunnell
Michael Hamrah
Nimish Parmar
Commissioning Editor
Kunal Parikh
Acquisition Editor
Richard Brookes-Bland
Content Development Editor
Govindan Kurumangattu
Technical Editor
Sebastian Rodrigues
Copy Editor
Vijay Tase
Project Coordinator
Shipra Chawhan
Proofreaders
Simran Bhogal
Maria Gould
Ameesha Green
Paul Hindle
Indexer
Hemangini Bari
Graphics
Abhinash Sahu
Production Coordinator
Komal Ramchandani
Cover Work
Komal Ramchandani
About the Author
Mat Ryer has a family legend (or conspiracy) that tells of him programming computers from the age of 6—he and his father would build games and programs, first BASIC on a ZX Spectrum then later AmigaBASIC and AMOS on their Commodore Amiga. Many hours were spent manually copying out code from the Amiga Format magazine, before spending more still tweaking variables or moving GOTO statements around to see what might happen. The same spirit of exploration and obsession with programming led Mat to start work for a local agency in Mansfield, England, when he was 18, where he started to build websites and services.
In 2006, Mat's wife, Laurie, took a job at the Science Museum in London, and so they both left rural Nottinghamshire for the big city, where Mat took a job at BT. It was here that he worked with a talented group of developers and managers on honing agile development skills and developing a light flavor that he still uses today.
After contracting around London for a few years, coding everything from C# and Objective-C to Ruby and JavaScript, Mat noticed a new systems language called Go that Google was pioneering. Because it addressed very pertinent and relevant modern technical challenges, Mat started using it to solve problems while the language was still in beta and he has used it ever since.
In 2012, Mat and Laurie left England to live in Boulder, Colorado, where Mat works on a variety of projects, from big data web services and highly available systems to small side projects and charitable endeavors.
Acknowledgments
I wouldn't have been able to write this book without the help of the wonderful Laurie Edwards, who, while working on her own projects, took the time to keep me organized and focused. Without her continuous and undying support, I dare say, this book (along with every other project I embark on) would never have happened.
Tyler Bunnell (@tylerb on GitHub)—who, believe it or not, I met on Google Code (working on the Goweb project)—is my Go life partner. We have paired on many projects so far, and will no doubt continue to do so into the future, until one of us (him) is tragically killed by the other due to some disagreement over proper use of the sync package! Tyler and I learned Go together, and he was also gracious enough to become a technical reviewer for this book—so in a way, you can blame any mistakes on him!
Other development heroes of mine include Ryan Quinn (@mazondo on GitHub), who seems to build an app a day and is living proof of how building something, however simple, is always better than building nothing. Thanks also go out to Tim Schreiner for engaging in debates with me over the good and bad bits of Go as well as being my go-to guy on matters close to and beyond the fringes of computer science.
Thanks go to the core Go team for building such a fun language and to the entire Go community who have saved me months of development with their contributions.
Special thanks also go to everyone who has supported me and helped me make doing what I love into a career, including but not limited to Nick Ryer (my dad, for getting me into computers in the first place), Maggie Ryer, Chris Ryer, Glenn Wilson, Phil Jackson, Jeff Cavins, Simon Howard, Edd Grant, Alan Meade, Steve Cart, Andy Jackson, Aditya Pradana, Andy Joslin, Simon Howard, Phil Edwards, Tracey Edwards, and all my other great friends and family.
About the Reviewers
Tyler Bunnell (@tylerb on GitHub) is an entrepreneur and developer whose inquisitive personality has enabled him to become an avid problem solver, seeking out knowledge and solutions and always aiming to be innovative and ahead of the curve.
His programming portfolio is interestingly eclectic; he cofounded Mizage, where he created a line of OS X applications, including Divvy, before partnering with a vocal coach to create Voice Tutor for iOS—an application that helps everyone sing without the need for private lessons. In 2012, Tyler took an interest in an emerging language, Go, where he made an immediate impact with contributions to the Go open source community by cofounding popular projects such as Testify, Graceful, and Genny, amongst other things. Most recently, he has turned his attention to an exciting new start-up, but he can't talk about that one just yet.
Michael Hamrah is a software engineer from Brooklyn, New York, who specializes in scalable, distributed systems for the Web with a focus on API design, event-driven asynchronous programming, and data modeling and storage. He works primarily with Scala and Go, and has extensive experience with all levels of the software stack. He can be reached via LinkedIn at https://www.linkedin.com/in/hamrah.
Nimish Parmar has over 10 years of experience building high performance distributed systems. After receiving his bachelor's degree in computer engineering from the University of Mumbai, Nimish completed a master of science in computer science from the University of Southern California. He was the technical reviewer for the book Amazon Web Services: Migrating your .NET Enterprise Application, Packt Publishing
He's currently working as a senior software engineer at StumbleUpon in San Francisco. Nimish is a die-hard USC Trojans football fan and enjoys snowboarding during winter.
I'd like to thank my parents, Ragini and Bipin. Words can't describe how fortunate I am to have received your endless love and support.
www.PacktPub.com
Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely-free books. Simply use your login credentials for immediate access.
Preface
I decided to write Go Programming Blueprints because I wanted to expel the myth that Go, being a relatively young language and community, is a bad choice for writing and iterating on software quickly. I have a friend who knocks out complete Ruby on Rails apps in a weekend by mashing up pre-existing gems and libraries; Rails as a platform has become known for enabling rapid development. Since I do the same with Go and the ever-growing buffet of open source packages, I wanted to share some real-world examples of how we can quickly build and release software that performs great from day one and is ready to scale when our projects take off in a way that Rails cannot compete with. Of course, most scalability happens outside the language, but features like Go's built-in concurrency mean you can get some very impressive results from even the most basic hardware, giving you a head start when things start to get real.
This book explores five very different projects, any of which could form the basis of a genuine start-up. Whether it's a low-latency chat application, a domain name suggestion tool, a social polling and election service built on Twitter, or a random night out generator powered by Google Places, each chapter touches upon a variety of problems that most products or services written in Go will need to address. The solutions I present in the book are just one of many ways to tackle each project, and I would encourage you to make up your own mind about how I approached them. The concepts are more important than the code itself, but you'll hopefully pick up a few tips and tricks here and there that can go into your Go toolbelt.
The process by which I wrote this book might be interesting because it represents something about the philosophies adopted by many agile developers. I started by giving myself the challenge of building a real deployable product (albeit a simple one; minimum viable product if you will) before getting stuck into it and writing a version 1. Once I got it working, I would rewrite it from scratch. It has been said many times by novelists and journalists that the art of writing is rewriting; I have found this to be true for software as well. The first time we write a piece of code, all we are really doing is learning about the problem and how it might be tackled as well as getting some of our thinking out of our heads and onto paper (or into a text editor). The second time we write it, we are applying our new knowledge to actually solve the problem. If you've never tried this, give it a shot—you might find that the quality of your code shoots up quite dramatically as I did. It doesn't mean the second time will be the last time—software evolves and we should try to keep it as cheap and disposable as possible, so we don't mind throwing pieces away if they go stale or start to get in the way.
I write all of my code following Test-driven Development (TDD) practices, some of which we will do together throughout the chapters and some you'll just see the result of in the final code. All of the test code can be found in the GitHub repositories for this book even if it's not included in print.
Once I had my test-driven second versions completed, I would start writing the chapter describing how and why I did what I did. In most cases, the iterative approach I took is left out of the book because it would just add pages of tweaks and edits, which would likely just become frustrating for the reader. However, on a couple of occasions, we will iterate together to get a feel of how a process of gradual improvements and small iterations (starting and keeping it simple and introducing complexity only when absolutely necessary) can be applied when writing Go packages and programs.
I moved to the United States from England in 2012, but that is not why the chapters are authored in American English; it was a requirement from the publisher. I suppose this book is aimed at an American audience, or perhaps it's because American English is the standard language of computing (in British code, properties that deal with color are spelled without the U). Either way, I apologize in advance for any trans-Atlantic slips; I know how pedantic programmers can be.
Any questions, improvements, suggestions, or debates (I love how opinionated the Go community—as well as the core team and the language itself—is) are more than welcome. These should probably take place in the GitHub issues for the book set up specifically at https://github.com/matryer/goblueprints so that everybody can take part.
Finally, I would be thrilled if somebody forms a start-up based on any of these projects, or makes use of them in other places. I would love to hear about it; you can tweet me at @matryer and let me know either way.
What this book covers
Chapter 1, Chat Application with Web Sockets, shows how to build a complete web application that allows multiple people to have a real-time conversation right in their web browser. We see how the net/http package lets us serve HTML pages as well as connect to the client's browser with web sockets.
Chapter 2, Adding Authentication, shows how to add OAuth to our chat application so that we can keep track of who is saying what, but let them log in using Google, Facebook, or GitHub.
Chapter 3, Three Ways to Implement Profile Pictures, explains how to add profile pictures to the chat application taken from either the authentication service, the Gravitar.com web service, or by allowing users to upload their own picture from their hard drive.
Chapter 4, Command-line Tools to Find Domain Names, explores how easy building command-line tools is in Go and puts those skills to use to tackle the problem of finding the perfect domain name for our chat application. It also explores how easy Go makes it to utilize the standard in and standard out pipes to produce some pretty powerful composable tools.
Chapter 5, Building Distributed Systems and Working with Flexible Data, explains how to prepare for the future of democracy by building a highly scalable Twitter polling and vote counting engine powered by NSQ and MongoDB.
Chapter 6, Exposing Data and Functionality through a RESTful Data Web Service API, looks at how to expose the capabilities we built in Chapter 5, Building Distributed Systems and Working with Flexible Data, through a JSON web service, specifically how wrapping http.HandlerFunc functions gives us a powerful pipeline pattern.
Chapter 7, Random Recommendations Web Service, shows how to consume the Google Places API to generate a location-based random recommendations API that represents a fun way to explore any area. It also explores why it's important to keep internal data structures private, controlling the public view into the same data, as well as how to implement enumerators in Go.
Chapter 8, Filesystem Backup, helps to build a simple but powerful filesystem backup tool for our code projects and explore interacting with the filesystem using the os package from the Go standard library. It also looks at how Go's interfaces allow simple abstractions to yield powerful results.
Appendix, Good Practices for a Stable Go Environment, teaches us how to install Go from scratch on a new machine and discusses some of the environmental options we have and the impact they might have in the future. We will also consider how collaboration might influence some of our decisions as well as the impact open sourcing our packages might have.
What you need for this book
To compile and run the code from this book, you will need a computer capable of running an operating system that supports the Go toolset, a list of which can be found at https://golang.org/doc/install#requirements.
Appendix, Good Practices for a Stable Go Environment, has some useful tips to install Go and set up your development environment including how to work with the GOPATH environment variable.
Who this book is for
This book is for all Go programmers—from beginners looking to explore the language by building real projects to expert gophers with an interest in how the language can be applied in interesting ways.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: We can use functionality from other packages using the import keyword, after we have used go get to download them.
A block of code is set as follows:
package meander
type Cost int8
const (
_ Cost = iota
Cost1
Cost2
Cost3
Cost4
Cost5
)
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
package meander
type Cost int8
const (
_ Cost = iota
Cost1
Cost2
Cost3
Cost4
Cost5
)
Any command-line input or output is written as follows:
go build -o project && ./project
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Once you install Xcode, you open Preferences and navigate to the Downloads section.
Note
Warnings or important notes appear in a box