Book Image

The Go Workshop

By : Delio D'Anna, Andrew Hayes, Sam Hennessy, Jeremy Leasor, Gobin Sougrakpam, Dániel Szabó
Book Image

The Go Workshop

By: Delio D'Anna, Andrew Hayes, Sam Hennessy, Jeremy Leasor, Gobin Sougrakpam, Dániel Szabó

Overview of this book

The Go Workshop will take the pain out of learning the Go programming language (also known as Golang). It is designed to teach you to be productive in building real-world software. Presented in an engaging, hands-on way, this book focuses on the features of Go that are used by professionals in their everyday work. Each concept is broken down, clearly explained, and followed up with activities to test your knowledge and build your practical skills. Your first steps will involve mastering Go syntax, working with variables and operators, and using core and complex types to hold data. Moving ahead, you will build your understanding of programming logic and implement Go algorithms to construct useful functions. As you progress, you'll discover how to handle errors, debug code to troubleshoot your applications, and implement polymorphism using interfaces. The later chapters will then teach you how to manage files, connect to a database, work with HTTP servers and REST APIs, and make use of concurrent programming. Throughout this Workshop, you'll work on a series of mini projects, including a shopping cart, a loan calculator, a working hours tracker, a web page counter, a code checker, and a user authentication system. By the end of this book, you'll have the knowledge and confidence to tackle your own ambitious projects with Go.
Table of Contents (21 chapters)
Free Chapter
1. Variables and Operators
2. Logic and Loops

Encoding JSON

We have studied how to unmarshal JSON into a struct. We will now do the opposite: marshal a struct into JSON. When we talk about encoding JSON, what we mean is we are taking a Go struct and converting it to a JSON data structure. The typical scenario in which this is done is when you have a service that is responding to an HTTP request from a client. The client wants the data in a certain format, and this is frequently JSON. Another situation is that the data is stored in a NoSQL database and it requires JSON as the format, or even a traditional database that has a column with a data type of JSON.

We need to be able to Marshal the Go struct into a JSON-encoded structure. To be able to do this, we will need to import the encoding/json package. We will be using the json.Marshal function:

func Marshal(v interface{}) ([]byte, error)

The v becomes encoded as JSON. Typically, v is a struct. The Marshal() function returns the JSON encoding as a slice of bytes and an...