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

Responding


A big part of any API is responding to requests with a combination of status codes, data, errors, and sometimes headers – the net/http package makes all of this very easy to do. One option we have, which remains the best option for tiny projects or even the early stages of big projects, is to just build the response code directly inside the handler.

As the number of handlers grows, however, we will end up duplicating a lot of code and sprinkling representation decisions all over our project. A more scalable approach is to abstract the response code into helper functions.

For the first version of our API, we are going to speak only JSON, but we want the flexibility to add other representations later if we need to.

Create a new file called respond.go and add the following code:

func decodeBody(r *http.Request, v interface{}) error { 
  defer r.Body.Close() 
  return json.NewDecoder(r.Body).Decode(v) 
} 
func encodeBody(w http.ResponseWriter, r *http.Request, v  interface{}) error {...