Go Cookbook
eBook - ePub

Go Cookbook

Aaron Torres

Partager le livre
  1. 400 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et Android
eBook - ePub

Go Cookbook

Aaron Torres

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

Bridge the gap between basic understanding of Go and use of its advanced featuresAbout This Book‱ Discover a number of recipes and approaches to develop modern back-end applications‱ Put to use the best practices to combine the recipes for sophisticated parallel tools‱ This book is based on Go 1.8, which is the latest versionWho This Book Is ForThis book is for web developers, programmers, and enterprise developers. Basic knowledge of the Go language is assumed. Experience with back-end application development is not necessary, but may help understand the motivation behind some of the recipes.What You Will Learn‱ Test your application using advanced testing methodologies‱ Develop an awareness of application structures, interface design, and tooling‱ Create strategies for third-party packages, dependencies, and vendoring‱ Get to know tricks on treating data such as collections‱ Handle errors and cleanly pass them along to calling functions‱ Wrap dependencies in interfaces for ease of portability and testing‱ Explore reactive programming design patterns in GoIn DetailGo (a.k.a. Golang) is a statically-typed programming language first developed at Google. It is derived from C with additional features such as garbage collection, type safety, dynamic-typing capabilities, additional built-in types, and a large standard library.This book takes off where basic tutorials on the language leave off. You can immediately put into practice some of the more advanced concepts and libraries offered by the language while avoiding some of the common mistakes for new Go developers.The book covers basic type and error handling. It explores applications that interact with users, such as websites, command-line tools, or via the file system. It demonstrates how to handle advanced topics such as parallelism, distributed systems, and performance tuning. Lastly, it finishes with reactive and serverless programming in Go.Style and approachThis guide is a handy reference for developers to quickly look up Go development patterns. It is a companion to other resources and a reference that will be useful long after reading it through the first time. Each recipe includes working, simple, and tested code that can be used as a reference or foundation for your own applications.

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Go Cookbook est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Go Cookbook par Aaron Torres en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Ciencia de la computaciĂłn et Lenguajes de programaciĂłn. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
2017
ISBN
9781783286843

Microservices for Applications in Go

In this chapter the following recipes will be covered:
  • Working with web handlers, requests, and ResponseWriters
  • Using structs and closures for stateful handlers
  • Validating input for Go structs and user inputs
  • Rendering and content negotiation
  • Implementing and using middleware
  • Building a reverse proxy application
  • Exporting GRPC as a JSON API

Introduction

Out of the box, Go is an excellent choice for writing web applications. The built-in net/http packages combined with packages like html/template allow for fully-featured modern web applications out of the box. It's so easy that it encourages spinning up web interfaces for management of even basic long-running applications. Although the standard library is fully featured, there are still a large variety of third-party web packages for everything from routes to full-stack frameworks including these:
  • https://github.com/urfave/negroni
  • https://github.com/gin-gonic/gin
  • https://github.com/labstack/echo
  • http://www.gorillatoolkit.org/
  • https://github.com/julienschmidt/httprouter
The recipes in this chapter will focus on basic tasks you might run into when working with handlers, when navigating response and request objects, and in dealing with concepts such as middleware.

Working with web handlers, requests, and ResponseWriters

Go defines HandlerFuncs and a Handler interface with the following signatures:
 // HandlerFunc implements the Handler interface
type HandlerFunc func(http.ResponseWriter, *http.Request)

type Handler interface {
ServeHTTP(http.ResponseWriter, *http.Request)
}
By default, the net/http package makes extensive use of these types. For example, a route can be attached to a Handler or HandlerFunc interface. This recipe will explore creating a Handler interface, listening on a local port, and performing some operations on an http.ResponseWriter interface after processing http.Request. This should be considered the basis for Go web applications and RESTFul APIs.

Getting ready

Configure your environment according to these steps:
  1. Download and install Go on your operating system from https://golang.org/doc/install, and configure your GOPATH environment variable.
  2. Open a terminal/console application.
  3. Navigate to your GOPATH/src and create a project directory, such as $GOPATH/src/github.com/yourusername/customrepo.
All code will be run and modified from this directory.
  1. Optionally, install the latest tested version of the code using the go get github.com/agtorre/go-cookbook/ command.
  2. Install the curl command from https://curl.haxx.se/download.html.

How to do it...

These steps cover writing and running your application:
  1. From your terminal/console application, create and navigate to the chapter7/handlers directory.
  2. Copy tests from https://github.com/agtorre/go-cookbook/tree/master/chapter7/handlers or use this as an exercise to write some of your own code.
  3. Create a file called get.go with the following contents:
 package handlers

import (
"fmt"
"net/http"
)

// HelloHandler takes a GET parameter "name" and responds
// with Hello <name>! in plaintext
func HelloHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
name := r.URL.Query().Get("name")

w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf("Hello %s!", name)))
}
  1. Create a file called post.go with the following contents:
 package handlers

import (
"encoding/json"
"net/http"
)

// GreetingResponse is the JSON Response that
// GreetingHandler returns
type GreetingResponse struct {
Payload struct {
Greeting string `json:"greeting,omitempty"`
Name string `json:"name,omitempty"`
Error string `json:"error,omitempty"`
} `json:"payload"`
Successful bool `json:"successful"`
}

// GreetingHandler returns a GreetingResponse which either has
// errors or a useful payload
func GreetingHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var gr GreetingResponse
if err := r.ParseForm(); err != nil {
gr.Payload.Error = "bad request"
if payload, err := json.Marshal(gr); err == nil {
w.Write(payload)
}
}
name := r.FormValue("name")
greeting := r.FormValue("greeting")

w.WriteHeader(http.StatusOK)
gr.Successful = true
gr.Payload.Name = name
gr.Payload.Greeting = greeting
if payload, err := json.Marshal(gr); err == nil {
w.Write(payload)
}
}
  1. Create a new directory named example and navigate to it.
  2. Create a file called main.go with the following contents; be sure to modify the handlers import to use the path you set up in step 2:
 package main

import (
"fmt"
"net/http"

"github.com/agtorre/go-cookbook/chapter7/handlers"
)

func main() {
http.HandleFunc("/name", handlers.HelloHandler)
http.HandleFunc("/greeting", handlers.GreetingHandler)
fmt.Println("Listening on port :3333")
err := http.ListenAn...

Table des matiĂšres