Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Go: Design Patterns for Real-World Projects

You're reading from   Go: Design Patterns for Real-World Projects Build production-ready solutions in Go using cutting-edge technology and techniques

Arrow left icon
Product type Course
Published in Jun 2017
Publisher Packt
ISBN-13 9781788390552
Length 1091 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (3):
Arrow left icon
Mario Castro Contreras Mario Castro Contreras
Author Profile Icon Mario Castro Contreras
Mario Castro Contreras
Mat Ryer Mat Ryer
Author Profile Icon Mat Ryer
Mat Ryer
Vladimir Vivien Vladimir Vivien
Author Profile Icon Vladimir Vivien
Vladimir Vivien
Arrow right icon
View More author details
Toc

Table of Contents (38) Chapters Close

Go: Design Patterns for Real-World Projects
Credits
Preface
Bibliography
1. A First Step in Go FREE CHAPTER 2. Go Language Essentials 3. Go Control Flow 4. Data Types 5. Functions in Go 6. Go Packages and Programs 7. Composite Types 8. Methods, Interfaces, and Objects 9. Concurrency 10. Data IO in Go 11. Writing Networked Services 12. Code Testing 13. Ready... Steady... Go! 14. Creational Patterns - Singleton, Builder, Factory, Prototype, and Abstract Factory Design Patterns 15. Structural Patterns - Composite, Adapter, and Bridge Design Patterns 16. Structural Patterns - Proxy, Facade, Decorator, and Flyweight Design Patterns 17. Behavioral Patterns - Strategy, Chain of Responsibility, and Command Design Patterns 18. Behavioral Patterns - Template, Memento, and Interpreter Design Patterns 19. Behavioral Patterns - Visitor, State, Mediator, and Observer Design Patterns 20. Introduction to Gos Concurrency 21. Concurrency Patterns - Barrier, Future, and Pipeline Design Patterns 22. Concurrency Patterns - Workers Pool and Publish/Subscriber Design Patterns 23. Chat Application with Web Sockets 24. Adding User Accounts 25. Three Ways to Implement Profile Pictures 26. Command-Line Tools to Find Domain Names 27. Building Distributed Systems and Working with Flexible Data 28. Exposing Data and Functionality through a RESTful Data Web Service API 29. Random Recommendations Web Service 30. Filesystem Backup 31. Building a Q&A Application for Google App Engine 32. Micro-services in Go with the Go kit Framework 33. Deploying Go Applications Using Docker 1. Good Practices for a Stable Go Environment

Go tools


An early decision made by the Go core team was that all Go code should look familiar and obvious to everybody who speaks Go rather than each code base requiring additional learning in order for new programmers to understand it or work on it. This is an especially sensible approach when you consider open source projects, some of which have hundreds of contributors coming and going all the time.

There is a range of tools that can assist us in achieving the high standards set by the Go core team, and we will look at some of the tools in action in this section.

In your GOPATH location, create a new folder called tooling and create a new main.go file containing the following code verbatim:

package main 
import ( 
  "fmt" 
) 
func main() { 
  return 
  var name string 
  name = "Mat" 
  fmt.Println("Hello ", name) 
} 

The tight spaces and lack of indentation are deliberate as we are going to look at a very cool utility that comes with Go.

In a terminal, navigate to your new folder and run this:

go fmt -w

Note

At Gophercon 2014 in Denver, Colorado, most people learned that rather than pronouncing this little triad as format or f, m, t, it is actually pronounced as a word. Try saying it to yourself now: fhumt; it seems that computer programmers aren't weird enough without speaking an alien language to each other too!

You will notice that this little tool has actually tweaked our code file to ensure that the layout (or format) of our program matches Go standards. The new version is much easier to read:

package main  
import ( 
  "fmt" 
)  
func main() { 
  return 
  var name string 
  name = "Mat" 
  fmt.Println("Hello ", name) 
} 

The go fmt command cares about indentation, code blocks, unnecessary whitespace, unnecessary extra line feeds, and more. Formatting your code in this way is a great practice to ensure that your Go code looks like all other Go code.

Next, we are going to vet our program to make sure that we haven't made any mistakes or decisions that might be confusing to our users; we can do this automatically with another great tool that we get for free:

go vet

The output for our little program points out an obvious and glaring mistake:

main.go:10: unreachable code
exit status 1

We are calling return at the top of our function and then trying to do other things. The go vet tool has noticed this and points out that we have unreachable code in our file.

It isn't just silly mistakes like this that go vet will catch; it will also look for subtler aspects of your program that will guide you toward writing the best Go code you can. For an up-to-date list of what the vet tool will report on, check out the documentation at https://golang.org/cmd/vet/.

The final tool we will play with is called goimports, and it was written by Brad Fitzpatrick to automatically fix (add or remove) import statements for Go files. It is an error in Go to import a package and not use it, and obviously, trying to use a package without importing it won't work either. The goimports tool will automatically rewrite our import statement based on the contents of our code file. First, let's install goimports with this familiar command:

go get golang.org/x/tools/cmd/goimports

Update your program to import some packages that we are not going to use and remove the fmt package:

import ( 
  "net/http" 
  "sync" 
) 

When we try to run our program by calling go run main.go, we will see that we get some errors:

./main.go:4: imported and not used: "net/http"
./main.go:5: imported and not used: "sync"
./main.go:13: undefined: fmt

These errors tell us that we have imported packages that we are not using and missing the fmt package and that in order to continue, we need to make corrections. This is where goimports comes in:

goimports -w *.go

We are calling the goimports command with the -w write flag, which will save us the task of making corrections to all files ending with .go.

Have a look at your main.go file now, and note that the net/http and sync packages have been removed and the fmt package has been put back in.

You could argue that switching to a terminal to run these commands takes more time than just doing it manually, and you would probably be right in most cases, which is why it is highly recommended that you integrate the Go tools with your text editor.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime