Go: Design Patterns for Real-World Projects Build production-ready solutions in Go using cutting-edge technology and techniques A course in three modules BIRMINGHAM - MUMBAI Go: Design Patterns for Real-World Projects Copyright © 2017 Packt Publishing Published on: June, 2017 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78839-055-2 www.packtpub.com Preface The Go programming language has firmly established itself as a favorite for building complex and scalable system applications. Go offers a direct and practical approach to programming that lets programmers write correct and predictable code using concurrency idioms and a full-featured standard library. What this learning path covers Module 1, Learning Go programming, is a step-by-step, practical guide full of real world examples to help you get started with Go in no time at all. We start off by understanding the fundamentals of Go, followed by a detailed description of the Go data types, program structures and Maps. After this, you learn how to use Go concurrency idioms to avoid pitfalls and create programs that are exact in expected behavior. Next, you will be familiarized with the tools and libraries that are available in Go for writing and exercising tests, benchmarking, and code coverage. Finally, you will be able to utilize some of the most important features of GO such as, Network Programming and OS integration to build efficient applications. All the concepts are explained in a crisp and concise manner and by the end of this module; you would be able to create highly efficient programs that you can deploy over cloud. Module 2, Go Design Patterns, will provide readers with a reference point to software design patterns and CSP concurrency design patterns to help them build applications in a more idiomatic, robust, and convenient way in Go. The module starts with a brief introduction to Go programming essentials and quickly moves on to explain the idea behind the creation of design patterns and how they appeared in the 90's as a common "language" between developers to solve common tasks in object-oriented programming languages. You will then learn how to apply the 23 Gang of Four (GoF) design patterns in Go and also learn about CSP concurrency patterns, the "killer feature" in Go that has helped Google develop software to maintain thousands of servers. With all of this the module will enable you to understand and apply design patterns in an idiomatic way that will produce concise, readable, and maintainable software. Module 3, Go Programming Blueprints - Second Edition, will show you how to leverage all the latest features and much more. This module 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 module 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. What you need for this learning path Module 1: To follow the examples in this module, you will need Go version 1.6 or later. Go supports architectures including AMD64, x386, and ARM running the following operating systems: • Windows XP (or later) • Mac OSX 10.7 (or later) • Linux 2.6 (or later) • FreeBSD 8 (or later) Module 2: Most of the chapters in this module are written following a simple TDD approach, here the requirements are written first, followed by some unit tests and finally the code that satisfies those requirements. We will use only tools that comes with the standard library of Go as a way to better understand the language and its possibilities. This idea is key to follow the module and understanding the way that Go solves problems, especially in distributed systems and concurrent applications. Module 3: To compile and run the code from this module, 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 learning path is for Beginners to Go who are comfortable in other OOP languages like Java, C# or Python will find this course interesting and beneficial. Reader feedback Feedback from our readers is always welcome. Let us know what you think about this course—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the course's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a course, see our author guide at www.packtpub.com/authors. Customer support Now that you are the proud owner of a Packt course, we have a number of things to help you to get the most from your purchase. Downloading the example code You can download the example code files for this course from your account at http://www.packtpub.com. If you purchased this course elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps: 1. Log in or register to our website using your e-mail address and password. 2. Hover the mouse pointer on the SUPPORT tab at the top. 3. Click on Code Downloads & Errata. 4. Enter the name of the course in the Search box. 5. Select the course for which you're looking to download the code files. 6. Choose from the drop-down menu where you purchased this course from. 7. Click on Code Download. You can also download the code files by clicking on the Code Files button on the course's webpage at the Packt Publishing website. This page can be accessed by entering the course's name in the Search box. Please note that you need to be logged in to your Packt account. Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of: • WinRAR / 7-Zip for Windows • Zipeg / iZip / UnRarX for Mac • 7-Zip / PeaZip for Linux The code bundle for the course is also hosted on GitHub at https://github.com/ PacktPublishing/Go-Design-Patterns-for-Real-World-Projects. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out! Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our courses—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this course. If you find any errata, please report them by visiting http://www. packtpub.com/submit-errata, selecting your course, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/ content/support and enter the name of the course in the search field. The required information will appear under the Errata section. Module 1: Learning Go Programming Chapter 1: A First Step in Go 7 The Go programming language 8 Playing with Go 10 No IDE required 11 Installing Go 11 Source code examples 12 Your first Go program 12 Go in a nutshell 13 Functions 15 Packages 16 The workspace 16 Strongly typed 16 Composite types 17 The named type 18 Methods and objects 18 Interfaces 19 Concurrency and channels 20 Memory management and safety 21 Fast compilation 22 Testing and code coverage 22 Documentation 23 An extensive library 24 The Go Toolchain 25 Summary 25 Chapter 2: Go Language Essentials 26 The Go source file 27 Optional semicolon 29 Multiple lines 30 Go identifiers 32 The blank identifier 32 Muting package imports 32 Muting unwanted function results 33 Built-in identifiers 33 Types 33 Values 34 Functions 34 Go variables 34 Variable declaration 34 The zero-value 36 Initialized declaration 36 Omitting variable types 37 Short variable declaration 39 Restrictions for short variable declaration 40 Variable scope and visibility 40 Variable declaration block 42 Go constants 42 Constant literals 42 Typed constants 43 Untyped constants 43 Assigning untyped constants 44 Constant declaration block 45 Constant enumeration 46 Overriding the default enumeration type 47 Using iota in expressions 47 Skipping enumerated values 48 Go operators 49 Arithmetic operators 49 The increment and decrement operators 49 Go assignment operators 50 Bitwise operators 50 Logical Operators 51 Comparison operators 51 Operator precedence 52 Summary 52 Chapter 3: Go Control Flow 53 The if statement 53 The if statement initialization 57 Switch statements 57 Using expression switches 59 The fallthrough cases 60 Expressionless switches 62 Switch initializer 63 [ ii ] Type switches 64 The for statements 66 For condition 66 Infinite loop 67 The traditional for statement 68 The for range 70 The break, continue, and goto statements 73 The label identifier 73 The break statement 73 The continue statement 74 The goto statement 75 Summary 76 Chapter 4: Data Types 77 Go types 77 Numeric types 80 Unsigned integer types 81 Signed integer types 81 Floating point types 82 Complex number types 82 Numeric literals 82 Boolean type 84 Rune and string types 84 The rune 85 The string 86 Interpreted and raw string literals 87 Pointers 88 The pointer type 89 The address operator 89 The new() function 91 Pointer indirection - accessing referenced values 92 Type declaration 93 Type conversion 94 Summary 96 Chapter 5: Functions in Go 97 Go functions 97 Function declaration 98 The function type 101 Variadic parameters 102 [ iii ] Function result parameters 103 Named result parameters 104 Passing parameter values 105 Achieving pass-by-reference 106 Anonymous Functions and Closures 107 Invoking anonymous function literals 108 Closures 108 Higher-order functions 109 Error signaling and handling 110 Signaling errors 111 Error handling 114 The error type 114 Deferring function calls 115 Using defer 117 Function panic and recovery 117 Function panic 117 Function panic recovery 119 Summary 121 Chapter 6: Go Packages and Programs 122 The Go package 122 Understanding the Go package 122 The workspace 124 Creating a workspace 126 The import path 127 Creating packages 128 Declaring the package 129 Multi-File packages 130 Naming packages 131 Use globally unique namespaces 131 Add context to path 132 Use short names 132 Building packages 133 Installing a package 134 Package visibility 134 Package member visibility 135 Importing package 136 Specifying package identifiers 138 The dot identifier 139 The blank identifier 139 [ iv ]