Go Programming Cookbook
eBook - ePub

Go Programming Cookbook

Over 85 recipes to build modular, readable, and testable Golang applications across various domains, 2nd Edition

Aaron Torres

Buch teilen
  1. 434 Seiten
  2. English
  3. ePUB (handyfreundlich)
  4. Über iOS und Android verfügbar
eBook - ePub

Go Programming Cookbook

Over 85 recipes to build modular, readable, and testable Golang applications across various domains, 2nd Edition

Aaron Torres

Angaben zum Buch
Buchvorschau
Inhaltsverzeichnis
Quellenangaben

Über dieses Buch

Tackle the trickiest of problems in Go programming with this practical guide

Key Features

  • Develop applications for different domains using modern programming techniques
  • Tackle common problems when it comes to parallelism, concurrency, and reactive programming in Go
  • Work with ready-to-execute code based on the latest version of Go

Book Description

Go (or Golang) is a statically typed programming language developed at Google. Known for its vast standard library, it also provides features such as garbage collection, type safety, dynamic-typing capabilities, and additional built-in types. This book will serve as a reference while implementing Go features to build your own applications.

This Go cookbook helps you put into practice the advanced concepts and libraries that Golang offers. The recipes in the book follow best practices such as documentation, testing, and vendoring with Go modules, as well as performing clean abstractions using interfaces. You'll learn how code works and the common pitfalls to watch out for. The book covers basic type and error handling, and then moves on to explore applications, such as websites, command-line tools, and filesystems, that interact with users. You'll even get to grips with parallelism, distributed systems, and performance tuning.

By the end of the book, you'll be able to use open source code and concepts in Go programming to build enterprise-class applications without any hassle.

What you will learn

  • Work with third-party Go projects and modify them for your use
  • Write Go code using modern best practices
  • Manage your dependencies with the new Go module system
  • Solve common problems encountered when dealing with backend systems or DevOps
  • Explore the Go standard library and its uses
  • Test, profile, and fine-tune Go applications

Who this book is for

If you're a web developer, programmer, or enterprise developer looking for quick solutions to common and not-so-common problems in Go programming, this book is for you. Basic knowledge of the Go language is assumed.

Häufig gestellte Fragen

Wie kann ich mein Abo kündigen?
Gehe einfach zum Kontobereich in den Einstellungen und klicke auf „Abo kündigen“ – ganz einfach. Nachdem du gekündigt hast, bleibt deine Mitgliedschaft für den verbleibenden Abozeitraum, den du bereits bezahlt hast, aktiv. Mehr Informationen hier.
(Wie) Kann ich Bücher herunterladen?
Derzeit stehen all unsere auf Mobilgeräte reagierenden ePub-Bücher zum Download über die App zur Verfügung. Die meisten unserer PDFs stehen ebenfalls zum Download bereit; wir arbeiten daran, auch die übrigen PDFs zum Download anzubieten, bei denen dies aktuell noch nicht möglich ist. Weitere Informationen hier.
Welcher Unterschied besteht bei den Preisen zwischen den Aboplänen?
Mit beiden Aboplänen erhältst du vollen Zugang zur Bibliothek und allen Funktionen von Perlego. Die einzigen Unterschiede bestehen im Preis und dem Abozeitraum: Mit dem Jahresabo sparst du auf 12 Monate gerechnet im Vergleich zum Monatsabo rund 30 %.
Was ist Perlego?
Wir sind ein Online-Abodienst für Lehrbücher, bei dem du für weniger als den Preis eines einzelnen Buches pro Monat Zugang zu einer ganzen Online-Bibliothek erhältst. Mit über 1 Million Büchern zu über 1.000 verschiedenen Themen haben wir bestimmt alles, was du brauchst! Weitere Informationen hier.
Unterstützt Perlego Text-zu-Sprache?
Achte auf das Symbol zum Vorlesen in deinem nächsten Buch, um zu sehen, ob du es dir auch anhören kannst. Bei diesem Tool wird dir Text laut vorgelesen, wobei der Text beim Vorlesen auch grafisch hervorgehoben wird. Du kannst das Vorlesen jederzeit anhalten, beschleunigen und verlangsamen. Weitere Informationen hier.
Ist Go Programming Cookbook als Online-PDF/ePub verfügbar?
Ja, du hast Zugang zu Go Programming Cookbook von Aaron Torres im PDF- und/oder ePub-Format sowie zu anderen beliebten Büchern aus Informatique & Programmation. Aus unserem Katalog stehen dir über 1 Million Bücher zur Verfügung.

Information

Jahr
2019
ISBN
9781789804706
Web Clients and APIs
Working with APIs and writing web clients can be a tricky business. Different APIs have different types of authorization, authentication, and protocol. We'll explore the http.Client structure object, work with OAuth2 clients and long-term token storage, and finish off with GRPC and an additional REST interface.
By the end of this chapter, you should have an idea of how to interface with third-party or in-house APIs and have some patterns for common operations, such as async requests to APIs.
In this chapter, we will cover the following recipes:
  • Initializing, storing, and passing http.Client structures
  • Writing a client for a REST API
  • Executing parallel and async client requests
  • Making use of OAuth2 clients
  • Implementing an OAuth2 token storage interface
  • Wrapping a client in added functionality and function composition
  • Understanding GRPC clients
  • Using twitchtv/twirp for RPC

Technical requirements

In order to proceed with all the recipes in this chapter, configure your environment according to these steps:
  1. Download and install Go 1.12.6 or higher on youroperatingsystem athttps://golang.org/doc/install.
  2. Open a Terminal or console application, create a project directory such as ~/projects/go-programming-cookbook, and navigate to this directory. All code will be run and modified from this directory.
  1. Clone the latest code into~/projects/go-programming-cookbook-original and optionally work from that directory rather than typing the examples manually, as follows:
 $ git clone [email protected]:PacktPublishing/Go-Programming-Cookbook-Second-Edition.git go-programming-cookbook-original 

Initializing, storing, and passing http.Client structures

The Go net/http package exposes a flexible http.Client structure for working with HTTP APIs. This structure has separate transport functionality and makes it relatively simple to short-circuit requests, modify headers for each client operation, and handle any REST operations. Creating clients is a very common operation, and this recipe will start with the basics of working and creating an http.Client object.

How to do it...

These steps cover writing and running of your application:
  1. From your Terminal or console application, create a new directory called ~/projects/go-programming-cookbook/chapter7/client, and navigate to this directory.
  2. Run the following command:
 $ go mod init github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter7/client
You should see a file calledgo.mod containing the following:
module github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter7/client
  1. Copy tests from~/projects/go-programming-cookbook-original/chapter7/client, or use this as an exercise to write some code of your own!
  1. Create a file called client.go with the following content:
 package client

import (
"crypto/tls"
"net/http"
)

// Setup configures our client and redefines
// the global DefaultClient
func Setup(isSecure, nop bool) *http.Client {
c := http.DefaultClient

// Sometimes for testing, we want to
// turn off SSL verification
if !isSecure {
c.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: false,
},
}
}
if nop {
c.Transport = &NopTransport{}
}
http.DefaultClient = c
return c
}

// NopTransport is a No-Op Transport
type NopTransport struct {
}

// RoundTrip Implements RoundTripper interface
func (n *NopTransport) RoundTrip(*http.Request)
(*http.Response, error) {
// note this is an uninitialized Response
// if you're looking at headers and so on.
return &http.Response{StatusCode: http.StatusTeapot}, nil
}
  1. Create a file called exec.go with the following content:
 package client

import (
"fmt"
"net/http"
)

// DoOps takes a client, then fetches
// google.com
func DoOps(c *http.Client) error {
resp, err := c.Get("http://www.google.com")
if err != nil {
return err
}
fmt.Println("results of DoOps:", resp.StatusCode)

return nil
}

// DefaultGetGolang uses the default client
// to get golang.org
func DefaultGetGolang() error {
resp, err := http.Get("https://www.golang.org")
if err != nil {
return err
}
fmt.Println("results of DefaultGetGolang:",
resp.StatusCode)
return nil
}
  1. Create a file called store.go with the following content:
 package client

import (
"fmt"
"net/http"
)

// Controller embeds an http.Client
// and uses it internally
type Controller struct {
*http.Client
}

// DoOps with a controller object
func (c *Controller) DoOps() error {
resp, err := c.Client.Get("http://www.google.com")
if err != nil {
return err
}
fmt.Println("results of client.DoOps", resp.StatusCode)
return nil
}
  1. Create a new directory called example and navigate to it.
  2. Create a file namedmain.gowith the following content:
 package main

import "github.com/PacktPublishing/
Go-Programming-Cookbook-Second-Edition/
chapter7/client"

func main() {
// secure and op!
cli := client.Setup(true, false)

if err := client.DefaultGetGolang(); err != nil {
panic(err)
}

if err := client.DoOps(cli); err != nil {
panic(err)
}

c := client.Controller{Client: cli}
if err := c.DoOps(); err != nil {
panic(err)
}

// secure and noop
// also modifies default
client.Setup(true, true)

if err := client.DefaultGetGolang(); err != nil {
panic(err)
}
}
  1. Run go run main.go.
  2. You may also run the following command:
 $ go build
$ ./example
You should now see the following output:
 $ go run main.go 
results of DefaultGetGolang: 200
results of DoOps: 200
results of client.DoOps 200
results of DefaultGetGolang: 418
  1. If you copied or wrote your own tests, go up one directory and run go test. Ensure that all the tests pass.

How it works...

The net/http package exposes a DefaultCl...

Inhaltsverzeichnis