Go: Design Patterns for Real-World Projects

Book description

An insightful guide to learning the Go programming language

About This Book

  • Get insightful coverage of Go programming syntax, constructs, and idioms to help you understand Go code

  • Get a full explanation of all the known GoF design patterns in Go, including comprehensive theory and examples

  • 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

  • Who This Book Is For

    Beginners to Go who are comfortable in other OOP languages like Java, C#, or Python will find this course interesting and beneficial.

    What You Will Learn

  • Install and configure the Go development environment to quickly get started with your first program

  • Use the basic elements of the language including source code structure, variables, constants, and control flow primitives

  • Get to know all the basic syntax and tools you need to start coding in Go

  • Create unique instances that cannot be duplicated within a program

  • Build quirky and fun projects from scratch while exploring patterns, practices, and techniques, as well as a range of different technologies

  • Create websites and data services capable of massive scaling using Go’s net/http package,

  • Explore RESTful patterns as well as low-latency WebSocket APIs

  • Interact with a variety of remote web services to consume capabilities, ranging from authentication and authorization to a fully functioning thesaurus

  • In Detail

    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. This practical guide is full of real-world examples to help you get started with Go in no time at all.

    You’ll start by understanding the fundamentals of Go, then get a detailed description of the Go data types, program structures, and Maps. After that, you’ll learn how to use Go concurrency idioms to avoid pitfalls and create programs that are exact in expected behavior. Next, you will get familiar with the tools and libraries that are available in Go to write and exercise tests, benchmarking, and code coverage. After that, 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.

    Then you’ll start applying your skills to build some amazing projects in Go. You will learn to develop high-quality command-line tools that utilize the powerful shell capabilities and perform well using Go’s built-in concurrency mechanisms. Scale, performance, and high availability lie at the heart of our projects, and the lessons learned throughout the sections 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. With these skills in hand, you will be able to conquer all your fears of application development and go on to build large, robust and succinct apps in Go.

    This Learning Path combines some of the best that Packt has to offer in one complete, curated package. It includes content from the following Packt products:

    1. Learning Go Programming

    2. Go Design Patterns

    3. Go Programming Blueprints, Second Edition

    Style and approach

    Full of real-world, practical examples, this course teaches you the widely used design patterns and best practices in Go in a step-by-step manner. It also provides fun projects that involve building applications from scratch.

    Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the code file.

    Table of contents

    1. Go: Design Patterns for Real-World Projects
      1. Go: Design Patterns for Real-World Projects
      2. Credits
      3. Preface
        1. What this learning path covers
        2. What you need for this learning path
        3. Who this learning path is for
        4. Reader feedback
        5. Customer support
          1. Downloading the example code
          2. Errata
          3. Piracy
          4. Questions
      4. 1. Module 1
        1. 1. A First Step in Go
          1. The Go programming language
          2. Playing with Go
            1. No IDE required
            2. Installing Go
            3. Source code examples
          3. Your first Go program
          4. Go in a nutshell
            1. Functions
            2. Packages
            3. The workspace
            4. Strongly typed
            5. Composite types
            6. The named type
            7. Methods and objects
            8. Interfaces
            9. Concurrency and channels
            10. Memory management and safety
            11. Fast compilation
            12. Testing and code coverage
            13. Documentation
            14. An extensive library
            15. The Go Toolchain
          5. Summary
        2. 2. Go Language Essentials
          1. The Go source file
            1. Optional semicolon
            2. Multiple lines
          2. Go identifiers
            1. The blank identifier
            2. Muting package imports
            3. Muting unwanted function results
            4. Built-in identifiers
              1. Types
              2. Values
              3. Functions
          3. Go variables
            1. Variable declaration
            2. The zero-value
            3. Initialized declaration
            4. Omitting variable types
            5. Short variable declaration
            6. Restrictions for short variable declaration
            7. Variable scope and visibility
            8. Variable declaration block
          4. Go constants
            1. Constant literals
            2. Typed constants
            3. Untyped constants
            4. Assigning untyped constants
            5. Constant declaration block
            6. Constant enumeration
            7. Overriding the default enumeration type
            8. Using iota in expressions
            9. Skipping enumerated values
          5. Go operators
            1. Arithmetic operators
            2. The increment and decrement operators
            3. Go assignment operators
            4. Bitwise operators
            5. Logical Operators
            6. Comparison operators
            7. Operator precedence
          6. Summary
        3. 3. Go Control Flow
          1. The if statement
            1. The if statement initialization
          2. Switch statements
            1. Using expression switches
            2. The fallthrough cases
            3. Expressionless switches
            4. Switch initializer
            5. Type switches
          3. The for statements
            1. For condition
            2. Infinite loop
            3. The traditional for statement
            4. The for range
          4. The break, continue, and goto statements
            1. The label identifier
            2. The break statement
            3. The continue statement
            4. The goto statement
          5. Summary
        4. 4. Data Types
          1. Go types
          2. Numeric types
            1. Unsigned integer types
            2. Signed integer types
            3. Floating point types
            4. Complex number types
            5. Numeric literals
          3. Boolean type
          4. Rune and string types
            1. The rune
            2. The string
            3. Interpreted and raw string literals
          5. Pointers
            1. The pointer type
            2. The address operator
            3. The new() function
            4. Pointer indirection - accessing referenced values
          6. Type declaration
          7. Type conversion
          8. Summary
        5. 5. Functions in Go
          1. Go functions
            1. Function declaration
            2. The function type
            3. Variadic parameters
            4. Function result parameters
              1. Named result parameters
          2. Passing parameter values
            1. Achieving pass-by-reference
            2. Anonymous Functions and Closures
            3. Invoking anonymous function literals
            4. Closures
          3. Higher-order functions
          4. Error signaling and handling
            1. Signaling errors
            2. Error handling
            3. The error type
          5. Deferring function calls
            1. Using defer
          6. Function panic and recovery
            1. Function panic
            2. Function panic recovery
          7. Summary
        6. 6. Go Packages and Programs
          1. The Go package
            1. Understanding the Go package
            2. The workspace
            3. Creating a workspace
            4. The import path
          2. Creating packages
            1. Declaring the package
            2. Multi-File packages
            3. Naming packages
              1. Use globally unique namespaces
              2. Add context to path
              3. Use short names
          3. Building packages
            1. Installing a package
          4. Package visibility
            1. Package member visibility
          5. Importing package
            1. Specifying package identifiers
            2. The dot identifier
            3. The blank identifier
          6. Package initialization
          7. Creating programs
            1. Accessing program arguments
            2. Building and installing programs
          8. Remote packages
          9. Summary
        7. 7. Composite Types
          1. The array type
            1. Array initialization
            2. Declaring named array types
            3. Using arrays
            4. Array length and capacity
            5. Array traversal
            6. Array as parameters
          2. The slice type
            1. Slice initialization
            2. Slice representation
            3. Slicing
            4. Slicing a slice
            5. Slicing an array
            6. Slice expressions with capacity
            7. Making a slice
            8. Using slices
            9. Slices as parameters
            10. Length and capacity
            11. Appending to slices
            12. Copying slices
            13. Strings as slices
          3. The map type
            1. Map initialization
            2. Making Maps
            3. Using maps
            4. Map traversal
            5. Map functions
              1. Maps as parameters
          4. The struct type
            1. Accessing struct fields
            2. Struct initialization
            3. Declaring named struct types
            4. The anonymous field
              1. Promoted fields
            5. Structs as parameters
            6. Field tags
          5. Summary
        8. 8. Methods, Interfaces, and Objects
          1. Go methods
            1. Value and pointer receivers
          2. Objects in Go
            1. The struct as object
            2. Object composition
            3. Field and method promotion
            4. The constructor function
          3. The interface type
            1. Implementing an interface
            2. Subtyping with Go interfaces
            3. Implementing multiple interfaces
            4. Interface embedding
            5. The empty interface type
          4. Type assertion
          5. Summary
        9. 9. Concurrency
          1. Goroutines
            1. The go statement
            2. Goroutine scheduling
          2. Channels
            1. The Channel type
              1. The send and receive operations
            2. Unbuffered channel
            3. Buffered channel
            4. Unidirectional channels
            5. Channel length and capacity
            6. Closing a channel
          3. Writing concurrent programs
            1. Synchronization
            2. Streaming data
            3. Using for…range to receive data
            4. Generator functions
            5. Selecting from multiple channels
            6. Channel timeout
          4. The sync package
            1. Synchronizing with mutex locks
            2. Synchronizing access to composite values
            3. Concurrency barriers with sync.WaitGroup
          5. Detecting race conditions
          6. Parallelism in Go
          7. Summary
        10. 10. Data IO in Go
          1. IO with readers and writers
          2. The io.Reader interface
            1. Chaining readers
          3. The io.Writer interface
          4. Working with the io package
          5. Working with files
            1. Creating and opening files
            2. Function os.OpenFile
            3. Files writing and reading
            4. Standard input, output, and error
          6. Formatted IO with fmt
            1. Printing to io.Writer interfaces
            2. Printing to standard output
            3. Reading from io.Reader
            4. Reading from standard input
          7. Buffered IO
            1. Buffered writers and readers
            2. Scanning the buffer
          8. In-memory IO
          9. Encoding and decoding data
            1. Binary encoding with gob
            2. Encoding data as JSON
            3. Controlling JSON mapping with struct tags
            4. Custom encoding and decoding
          10. Summary
        11. 11. Writing Networked Services
          1. The net package
            1. Addressing
            2. The net.Conn Type
            3. Dialing a connection
            4. Listening for incoming connections
            5. Accepting client connections
          2. A TCP API server
            1. Connecting to the TCP server with telnet
            2. Connecting to the TCP server with Go
          3. The HTTP package
            1. The http.Client type
            2. Configuring the client
            3. Handling client requests and responses
            4. A simple HTTP server
              1. The default server
            5. Routing requests with http.ServeMux
              1. The default ServeMux
          4. A JSON API server
            1. Testing the API server with cURL
            2. An API server client in Go
            3. A JavaScript API server client
          5. Summary
        12. 12. Code Testing
          1. The Go test tool
            1. Test file names
            2. Test organization
          2. Writing Go tests
            1. The test functions
            2. Running the tests
              1. Filtering executed tests
            3. Test logging
            4. Reporting failure
            5. Skipping tests
            6. Table-driven tests
          3. HTTP testing
            1. Testing HTTP server code
            2. Testing HTTP client code
          4. Test coverage
            1. The cover tool
          5. Code benchmark
            1. Running the benchmark
            2. Skipping test functions
            3. The benchmark report
            4. Adjusting N
            5. Comparative benchmarks
          6. Summary
      5. 2. Module 2
        1. 1. Ready... Steady... Go!
          1. A little bit of history
          2. Installing Go
            1. Linux
              1. Go Linux advanced installation
            2. Windows
            3. Mac OS X
            4. Setting the workspace - Linux and Apple OS X
          3. Starting with Hello World
          4. Integrated Development Environment - IDE
          5. Types
          6. Variables and constants
          7. Operators
          8. Flow control
            1. The if... else statement
            2. The switch statement
            3. The for…range statement
          9. Functions
            1. What does a function look like?
            2. What is an anonymous function?
            3. Closures
            4. Creating errors, handling errors and returning errors.
            5. Function with undetermined number of parameters
              1. Naming returned types
          10. Arrays, slices, and maps
            1. Arrays
              1. Zero-initialization
            2. Slices
            3. Maps
          11. Visibility
          12. Zero-initialization
          13. Pointers and structures
            1. What is a pointer? Why are they good?
            2. Structs
          14. Interfaces
            1. Interfaces - signing a contract
          15. Testing and TDD
            1. The testing package
            2. What is TDD?
          16. Libraries
          17. The Go get tool
          18. Managing JSON data
            1. The encoding package
          19. Go tools
            1. The golint tool
            2. The gofmt tool
            3. The godoc tool
            4. The goimport tool
          20. Contributing to Go open source projects in GitHub
          21. Summary
        2. 2. Creational Patterns - Singleton, Builder, Factory, Prototype, and Abstract Factory Design Patterns
          1. Singleton design pattern - having a unique instance of a type in the entire program
            1. Description
            2. Objectives
            3. Example - a unique counter
            4. Requirements and acceptance criteria
            5. Writing unit tests first
            6. Implementation
            7. A few words about the Singleton design pattern
          2. Builder design pattern - reusing an algorithm to create many implementations of an interface
            1. Description
            2. Objectives
            3. Example - vehicle manufacturing
            4. Requirements and acceptance criteria
            5. Unit test for the vehicle builder
            6. Implementation
            7. Wrapping up the Builder design pattern
          3. Factory method - delegating the creation of different types of payments
            1. Description
            2. Objectives
            3. The example - a factory of payment methods for a shop
            4. Acceptance criteria
            5. First unit test
            6. Implementation
            7. Upgrading the Debitcard method to a new platform
            8. What we learned about the Factory method
          4. Abstract Factory - a factory of factories
            1. Description
            2. The objectives
            3. The vehicle factory example, again?
            4. Acceptance criteria
            5. Unit test
            6. Implementation
            7. A few lines about the Abstract Factory method
          5. Prototype design pattern
            1. Description
            2. Objective
            3. Example
            4. Acceptance criteria
            5. Unit test
            6. Implementation
            7. What we learned about the Prototype design pattern
          6. Summary
        3. 3. Structural Patterns - Composite, Adapter, and Bridge Design Patterns
          1. Composite design pattern
            1. Description
            2. Objectives
            3. The swimmer and the fish
            4. Requirements and acceptance criteria
            5. Creating compositions
            6. Binary Tree compositions
            7. Composite pattern versus inheritance
            8. Final words on the Composite pattern
          2. Adapter design pattern
            1. Description
            2. Objectives
            3. Using an incompatible interface with an Adapter object
            4. Requirements and acceptance criteria
            5. Unit testing our Printer adapter
            6. Implementation
            7. Examples of the Adapter pattern in Go's source code
            8. What the Go source code tells us about the Adapter pattern
          3. Bridge design pattern
            1. Description
            2. Objectives
            3. Two printers and two ways of printing for each
            4. Requirements and acceptance criteria
            5. Unit testing the Bridge pattern
            6. Implementation
            7. Reuse everything with the Bridge pattern
          4. Summary
        4. 4. Structural Patterns - Proxy, Facade, Decorator, and Flyweight Design Patterns
          1. Proxy design pattern
            1. Description
            2. Objectives
            3. Example
            4. Acceptance criteria
            5. Unit test
            6. Implementation
            7. Proxying around actions
          2. Decorator design pattern
            1. Description
            2. Objectives
            3. Example
            4. Acceptance criteria
            5. Unit test
            6. Implementation
            7. A real-life example - server middleware
              1. Starting with the common interface, http.Handler
            8. A few words about Go's structural typing
            9. Summarizing the Decorator design pattern - Proxy versus Decorator
          3. Facade design pattern
            1. Description
            2. Objectives
            3. Example
            4. Acceptance criteria
            5. Unit test
            6. Implementation
            7. Library created with the Facade pattern
          4. Flyweight design pattern
            1. Description
            2. Objectives
            3. Example
            4. Acceptance criteria
            5. Basic structs and tests
            6. Implementation
            7. What's the difference between Singleton and Flyweight then?
          5. Summary
        5. 5. Behavioral Patterns - Strategy, Chain of Responsibility, and Command Design Patterns
          1. Strategy design pattern
            1. Description
            2. Objectives
            3. Rendering images or text
            4. Acceptance criteria
            5. Implementation
            6. Solving small issues in our library
            7. Final words on the Strategy pattern
          2. Chain of responsibility design pattern
            1. Description
            2. Objectives
            3. A multi-logger chain
            4. Unit test
            5. Implementation
            6. What about a closure?
            7. Putting it together
          3. Command design pattern
            1. Description
            2. Objectives
            3. A simple queue
            4. Acceptance criteria
            5. Implementation
            6. More examples
            7. Chain of responsibility of commands
            8. Rounding-up the Command pattern up
          4. Summary
        6. 6. Behavioral Patterns - Template, Memento, and Interpreter Design Patterns
          1. Template design pattern
            1. Description
            2. Objectives
            3. Example - a simple algorithm with a deferred step
            4. Requirements and acceptance criteria
            5. Unit tests for the simple algorithm
            6. Implementing the Template pattern
            7. Anonymous functions
            8. How to avoid modifications on the interface
            9. Looking for the Template pattern in Go's source code
            10. Summarizing the Template design pattern
          2. Memento design pattern
            1. Description
            2. Objectives
            3. A simple example with strings
            4. Requirements and acceptance criteria
            5. Unit test
            6. Implementing the Memento pattern
            7. Another example using the Command and Facade patterns
            8. Last words on the Memento pattern
          3. Interpreter design pattern
            1. Description
            2. Objectives
            3. Example - a polish notation calculator
            4. Acceptance criteria for the calculator
            5. Unit test of some operations
            6. Implementation
            7. Complexity with the Interpreter design pattern
            8. Interpreter pattern again - now using interfaces
            9. The power of the Interpreter pattern
          4. Summary
        7. 7. Behavioral Patterns - Visitor, State, Mediator, and Observer Design Patterns
          1. Visitor design pattern
            1. Description
            2. Objectives
            3. A log appender
            4. Acceptance criteria
            5. Unit tests
            6. Implementation of Visitor pattern
            7. Another example
            8. Visitors to the rescue!
          2. State design pattern
            1. Description
            2. Objectives
            3. A small guess the number game
            4. Acceptance criteria
            5. Implementation of State pattern
            6. A state to win and a state to lose
            7. The game built using the State pattern
          3. Mediator design pattern
            1. Description
            2. Objectives
            3. A calculator
            4. Acceptance criteria
            5. Implementation
            6. Uncoupling two types with the Mediator
          4. Observer design pattern
            1. Description
            2. Objectives
            3. The notifier
            4. Acceptance criteria
            5. Unit tests
            6. Implementation
            7. Summary
        8. 8. Introduction to Gos Concurrency
          1. A little bit of history and theory
            1. Concurrency versus parallelism
            2. CSP versus actor-based concurrency
          2. Goroutines
            1. Our first Goroutine
            2. Anonymous functions launched as new Goroutines
            3. WaitGroups
          3. Callbacks
            1. Callback hell
          4. Mutexes
            1. An example with mutexes - concurrent counter
            2. Presenting the race detector
          5. Channels
            1. Our first channel
            2. Buffered channels
            3. Directional channels
            4. The select statement
            5. Ranging over channels too!
          6. Using it all - concurrent singleton
            1. Unit test
            2. Implementation
          7. Summary
        9. 9. Concurrency Patterns - Barrier, Future, and Pipeline Design Patterns
          1. Barrier concurrency pattern
            1. Description
            2. Objectives
            3. An HTTP GET aggregator
            4. Acceptance criteria
            5. Unit test - integration
            6. Implementation
            7. Waiting for responses with the Barrier design pattern
          2. Future design pattern
            1. Description
            2. Objectives
            3. A simple asynchronous requester
            4. Acceptance criteria
            5. Unit tests
            6. Implementation
            7. Putting the Future together
          3. Pipeline design pattern
            1. Description
            2. Objectives
            3. A concurrent multi-operation
            4. Acceptance criteria
            5. Beginning with tests
            6. Implementation
              1. The list generator
              2. Raising numbers to the power of 2
              3. Final reduce operation
              4. Launching the Pipeline pattern
            7. Final words on the Pipeline pattern
          4. Summary
        10. 10. Concurrency Patterns - Workers Pool and Publish/Subscriber Design Patterns
          1. Workers pool
            1. Description
            2. Objectives
            3. A pool of pipelines
            4. Acceptance criteria
            5. Implementation
              1. The dispatcher
              2. The pipeline
            6. An app using the workers pool
            7. No tests?
            8. Wrapping up the Worker pool
          2. Concurrent Publish/Subscriber design pattern
            1. Description
            2. Objectives
            3. Example - a concurrent notifier
            4. Acceptance criteria
            5. Unit test
              1. Testing subscriber
              2. Testing publisher
            6. Implementation
              1. Implementing the publisher
              2. Handling channels without race conditions
            7. A few words on the concurrent Observer pattern
          3. Summary
      6. 3. Module 3
        1. 1. Chat Application with Web Sockets
          1. A simple web server
            1. Separating views from logic using templates
              1. Doing things once
              2. Using your own handlers
            2. Properly building and executing Go programs
          2. Modeling a chat room and clients on the server
            1. Modeling the client
            2. Modeling a room
            3. Concurrency programming using idiomatic Go
            4. Turning a room into an HTTP handler
            5. Using helper functions to remove complexity
            6. Creating and using rooms
          3. Building an HTML and JavaScript chat client
            1. Getting more out of templates
          4. Tracing code to get a look under the hood
            1. Writing a package using TDD
            2. Interfaces
            3. Unit tests
              1. Red-green testing
            4. Implementing the interface
              1. Unexported types being returned to users
            5. Using our new trace package
            6. Making tracing optional
            7. Clean package APIs
          5. Summary
        2. 2. Adding User Accounts
          1. Handlers all the way down
          2. Making a pretty social sign-in page
          3. Endpoints with dynamic paths
          4. Getting started with OAuth2
            1. Open source OAuth2 packages
          5. Tell the authorization providers about your app
          6. Implementing external logging in
            1. Logging in
            2. Handling the response from the provider
            3. Presenting the user data
            4. Augmenting messages with additional data
          7. Summary
        3. 3. Three Ways to Implement Profile Pictures
          1. Avatars from the OAuth2 server
            1. Getting the avatar URL
            2. Transmitting the avatar URL
            3. Adding the avatar to the user interface
            4. Logging out
            5. Making things prettier
          2. Implementing Gravatar
            1. Abstracting the avatar URL process
              1. The auth service and the avatar's implementation
              2. Using an implementation
              3. The Gravatar implementation
          3. Uploading an avatar picture
            1. User identification
            2. An upload form
            3. Handling the upload
            4. Serving the images
            5. The Avatar implementation for local files
              1. Supporting different file types
            6. Refactoring and optimizing our code
              1. Replacing concrete types with interfaces
              2. Changing interfaces in a test-driven way
              3. Fixing the existing implementations
              4. Global variables versus fields
              5. Implementing our new design
              6. Tidying up and testing
          4. Combining all three implementations
          5. Summary
        4. 4. Command-Line Tools to Find Domain Names
          1. Pipe design for command-line tools
          2. Five simple programs
            1. Sprinkle
            2. Domainify
            3. Coolify
            4. Synonyms
              1. Using environment variables for configuration
              2. Consuming a web API
              3. Getting domain suggestions
            5. Available
          3. Composing all five programs
            1. One program to rule them all
          4. Summary
        5. 5. Building Distributed Systems and Working with Flexible Data
          1. The system design
            1. The database design
          2. Installing the environment
            1. Introducing NSQ
              1. NSQ driver for Go
            2. Introducing MongoDB
              1. MongoDB driver for Go
            3. Starting the environment
          3. Reading votes from Twitter
            1. Authorization with Twitter
              1. Extracting the connection
              2. Reading environment variables
            2. Reading from MongoDB
            3. Reading from Twitter
              1. Signal channels
            4. Publishing to NSQ
            5. Gracefully starting and stopping programs
            6. Testing
          4. Counting votes
            1. Connecting to the database
            2. Consuming messages in NSQ
            3. Keeping the database updated
            4. Responding to Ctrl + C
          5. Running our solution
          6. Summary
        6. 6. Exposing Data and Functionality through a RESTful Data Web Service API
          1. RESTful API design
          2. Sharing data between handlers
            1. Context keys
          3. Wrapping handler functions
            1. API keys
            2. Cross-origin resource sharing
          4. Injecting dependencies
          5. Responding
          6. Understanding the request
          7. Serving our API with one function
            1. Using handler function wrappers
          8. Handling endpoints
            1. Using tags to add metadata to structs
            2. Many operations with a single handler
              1. Reading polls
              2. Creating a poll
              3. Deleting a poll
              4. CORS support
            3. Testing our API using curl
          9. A web client that consumes the API
            1. Index page showing a list of polls
            2. Creating a new poll
            3. Showing the details of a poll
          10. Running the solution
          11. Summary
        7. 7. Random Recommendations Web Service
          1. The project overview
            1. Project design specifics
          2. Representing data in code
            1. Public views of Go structs
          3. Generating random recommendations
            1. The Google Places API key
            2. Enumerators in Go
              1. Test-driven enumerator
            3. Querying the Google Places API
            4. Building recommendations
            5. Handlers that use query parameters
            6. CORS
            7. Testing our API
              1. Web application
          4. Summary
        8. 8. Filesystem Backup
          1. Solution design
            1. The project structure
          2. The backup package
            1. Considering obvious interfaces first
            2. Testing interfaces by implementing them
            3. Has the filesystem changed?
            4. Checking for changes and initiating a backup
              1. Hardcoding is OK for a short while
          3. The user command-line tool
            1. Persisting small data
            2. Parsing arguments
              1. Listing the paths
                1. String representations for your own types
              2. Adding paths
              3. Removing paths
            3. Using our new tool
          4. The daemon backup tool
            1. Duplicated structures
            2. Caching data
            3. Infinite loops
            4. Updating filedb records
          5. Testing our solution
          6. Summary
        9. 9. Building a Q&A Application for Google App Engine
          1. The Google App Engine SDK for Go
            1. Creating your application
            2. App Engine applications are Go packages
            3. The app.yaml file
            4. Running simple applications locally
            5. Deploying simple applications to Google App Engine
            6. Modules in Google App Engine
              1. Specifying modules
              2. Routing to modules with dispatch.yaml
          2. Google Cloud Datastore
            1. Denormalizing data
          3. Entities and data access
            1. Keys in Google Cloud Datastore
            2. Putting data into Google Cloud Datastore
            3. Reading data from Google Cloud Datastore
          4. Google App Engine users
            1. Embedding denormalized data
          5. Transactions in Google Cloud Datastore
            1. Using transactions to maintain counters
            2. Avoiding early abstraction
          6. Querying in Google Cloud Datastore
          7. Votes
            1. Indexing
            2. Embedding a different view of entities
          8. Casting a vote
            1. Accessing parents via datastore.Key
            2. Line of sight in code
          9. Exposing data operations over HTTP
            1. Optional features with type assertions
            2. Response helpers
            3. Parsing path parameters
            4. Exposing functionality via an HTTP API
              1. HTTP routing in Go
            5. Context in Google App Engine
            6. Decoding key strings
              1. Using query parameters
              2. Anonymous structs for request data
              3. Writing self-similar code
              4. Validation methods that return an error
            7. Mapping the router handlers
          10. Running apps with multiple modules
            1. Testing locally
              1. Using the admin console
                1. Automatically generated indexes
          11. Deploying apps with multiple modules
          12. Summary
        10. 10. Micro-services in Go with the Go kit Framework
          1. Introducing gRPC
          2. Protocol buffers
            1. Installing protocol buffers
            2. Protocol buffers language
            3. Generating Go code
          3. Building the service
            1. Starting with tests
            2. Constructors in Go
            3. Hashing and validating passwords with bcrypt
          4. Modeling method calls with requests and responses
            1. Endpoints in Go kit
              1. Making endpoints for service methods
              2. Different levels of error
              3. Wrapping endpoints into a Service implementation
          5. An HTTP server in Go kit
          6. A gRPC server in Go kit
            1. Translating from protocol buffer types to our types
          7. Creating a server command
            1. Using Go kit endpoints
            2. Running the HTTP server
            3. Running the gRPC server
            4. Preventing a main function from terminating immediately
            5. Consuming the service over HTTP
          8. Building a gRPC client
            1. A command-line tool to consume the service
            2. Parsing arguments in CLIs
            3. Maintaining good line of sight by extracting case bodies
            4. Installing tools from the Go source code
          9. Rate limiting with service middleware
            1. Middleware in Go kit
            2. Manually testing the rate limiter
            3. Graceful rate limiting
          10. Summary
        11. 11. Deploying Go Applications Using Docker
          1. Using Docker locally
            1. Installing Docker tools
            2. Dockerfile
            3. Building Go binaries for different architectures
            4. Building a Docker image
            5. Running a Docker image locally
            6. Inspecting Docker processes
            7. Stopping a Docker instance
          2. Deploying Docker images
            1. Deploying to Docker Hub
          3. Deploying to Digital Ocean
            1. Creating a droplet
            2. Accessing the droplet's console
            3. Pulling Docker images
            4. Running Docker images in the cloud
            5. Accessing Docker images in the cloud
          4. Summary
        12. Appendix. Good Practices for a Stable Go Environment
          1. Installing Go
          2. Configuring Go
            1. Getting GOPATH right
          3. Go tools
          4. Cleaning up, building, and running tests on save
          5. Integrated developer environments
            1. Sublime Text 3
            2. Visual Studio Code
          6. Summary
      7. Bibliography

    Product information

    • Title: Go: Design Patterns for Real-World Projects
    • Author(s): Vladimir Vivien, Mario Castro Contreras, Mat Ryer
    • Release date: June 2017
    • Publisher(s): Packt Publishing
    • ISBN: 9781788390552