logo资料库

Web Development with Go.pdf

第1页 / 共300页
第2页 / 共300页
第3页 / 共300页
第4页 / 共300页
第5页 / 共300页
第6页 / 共300页
第7页 / 共300页
第8页 / 共300页
资料共300页,剩余部分请下载后查看
Contents at a Glance
Contents
About the Author
About the Technical Reviewer
Introduction
Chapter 1: Getting Started with Go
Introducing Go
Minimalistic Language with Pragmatic Design
A Static Type Language with High Productivity
Concurrency Is a Built-In Feature at the Language Level
Go Compiles Programs Quickly
Go as a General-Purpose Language
Go Ecosystem
Installing the Go Tools
Checking the Installation
Setting up a Work Environment
Go Workspace
GOPATH Environment Variable
Code Organization Paths
Writing Go Programs
Writing a Hello World Program
Writing a Library
Testing Go Code
Using Go Playground
Using Go Mobile
Go as a Language for Web and Microservices
Summary
Chapter 2: Go Fundamentals
Packages
Package main
Package Alias
Function init
Using a Blank Identifier
Importing Packages
Install Third-Party Packages
Writing Packages
Go Tool
Formatting Go Code
Go Documentation
Working with Collections
Arrays
Slices
Creating a Slice with the make Function
Creating a Slice with Slice Literal
Slice Functions
Length and Capacity
Iterating Over Slices
Maps
Defer, Panic, and Recover
Defer
Panic
Recover
Error Handling
Summary
Chapter 3: User-Defined Types and Concurrency
User-defined Types with Structs
Creating a Struct Type
Creating Instances of Struct Types
Adding Behavior to a Struct Type
Calling Struct Methods
Pointer Method Receivers
Type Composition
Overriding Methods of Embedded Type
Working with Interfaces
Concurrency
Goroutines
GOMAXPROCS and Parallelism
Channels
Unbuffered Channel
Buffered Channels
Summary
Chapter 4: Getting Started with Web Development
net/http Package
Processing HTTP Requests
Serve Mux
Handler
Building a Static Web Server
Creating Custom Handlers
Using Functions as Handlers
http.HandlerFunc type
ServeMux.HandleFunc Function
DefaultServeMux
http.Server Struct
Gorilla Mux
Building a RESTful API
Data Model and Data Store
Configuring the Multiplexer
Handler Functions for CRUD Operations
Summary
Chapter 5: Working with Go Templates
text/template Package
Working with text/template
Define Named Templates
Declaring Variables
Using Pipes
Building HTML Views Using html/template
Building a Web Application
Data Structure and Data Store
main function
Views and Template Definition Files
Initializing View Templates
Rendering the Index Page
Rendering the Add Page
Rendering the Edit Page
Summary
Chapter 6: HTTP Middleware
Introduction to HTTP Middleware
Writing HTTP Middleware
How to Write HTTP Middleware
Writing a Logging Middleware
Controlling the Flow of HTTP Middleware
Using Third-Party Middleware
Using Gorilla Handlers
Installing Gorilla Handlers
Working with Gorilla Handlers
Middleware Chaining with the Alice Package
Installing Alice
Working with Alice
Using Middleware with the Negroni Package
Getting Started with Negroni
Installing Negroni
Routing with Negroni
Registering Middleware
Registering Middleware for Specific Routes
Working with a Negroni Middleware Stack
Sharing Values Among Middleware
Using Gorilla context
Setting and Getting Values with Gorilla context
Summary
Chapter 7: Authentication to Web Apps
Authentication and Authorization
Authentication Approaches
Cookie-Based Authentication
Token-Based Authentication
Authentication with OAuth 2
Understanding OAuth 2
Authentication with OAuth 2 using the Goth Package
Authentication with JSON Web Token
Working with JWT Using the jwt-go Package
Generating the JWT Token
Validating the JWT Token
Running and Testing the API Server
Using HTTP Middleware to Validate JWT Tokens
Summary
Chapter 8: Persistence with MongoDB
Introduction to MongoDB
Getting Started Using MongoDB
Introduction to mgo Driver for MongoDB
Installing mgo
Connecting to MongoDB
Accessing Collections
CRUD Operations with MongoDB
Inserting Documents
Inserting Struct Values
Inserting Embedded Documents
Reading Documents
Retrieving All Records
Sorting Records
Retrieving a Single Record
Updating Documents
Deleting Documents
Indexes in MongoDB
Managing Sessions
Summary
Chapter 9: Building RESTful Services
RESTful APIs: the Backbone of Digital Transformation
API-Driven Development with RESTful APIs
Go: the Great Stack for RESTful Services
Go: the Great Stack for Microservice Architecture
RESTful Services in Microservice Architecture
Building RESTful APIs
Third-Party Packages
Application Structure
Data Model
Resource Modeling for RESTful APIs
Mapping Resources with Application Routes
Routes for the Users Resource
Routes for the Tasks Resource
Adding Route-Specific Middleware
Routes for the TaskNote Resource
Initializing Routes for a RESTful API
Setting up the RESTful API Application
Initializing Configuration Values
Loading Private/Public RSA Keys
Creating a MongoDB Session Object
Adding Indexes into MongoDB
Initialization Logic in the common Package
Starting the HTTP Server
Authentication
Generating and Verifying JWT
Generating JWT
Sending JWT to the Server
Authorizing JWT
Application Handlers
Helper for Displaying HTTP Errors
Handling Data for an HTTP Request Lifecycle
Handlers for the Users Resource
JSON Resource Models
Handlers for the Users Resource
Registering New Users
Logging in to the System
Data Persistence with MongoDB
Handlers for the Tasks Resource
JSON Resource Models
Handlers for the Tasks Resource
Testing API Operations for the Tasks Resource
Handlers for Notes Resource
JSON Resource Models
Go Dependencies Using Godep
Installing the godep Tool
Using godep with TaskManager
Restoring an Application’s Dependencies
Deploying HTTP Servers with Docker
Introduction to Docker
Writing Dockerfile
Go Web Frameworks
Summary
References
Chapter 10: Testing Go Applications
Unit Testing
Test-Driven Development (TDD)
Unit Testing with Go
Writing Unit Tests
Getting Test Coverage
Benchmark Unit Tests
Verifying Example Code
Skipping Test Cases
Running Tests Cases in Parallel
Putting Tests in Separate Packages
Testing Web Applications
Testing with ResponseRecorder
Testing with Server
BDD Testing in Go
Behavior-Driven Development (BDD)
Behavior-Driven Development with Ginkgo
Refactoring the HTTP API
Writing BDD-style Tests
Installing Ginkgo and Gomega
Bootstrapping a Suite
Adding Specs to the Suite
Organizing Specs with Containers
Writing Specs in the Test File
Running Specs
Summary
Chapter 11: Building Go Web Applications on Google Cloud
Introduction to Cloud Computing
Infrastructure as a Service (IaaS)
Platform as a Service (PaaS)
Container as a Service
Introduction to Google Cloud
Google App Engine (GAE)
Cloud Services with App Engine
User Authentication
Cloud Datastore
Cloud Bigtable
Google Cloud SQL
Memcache
Search
Traffic Splitting
Logging
Task Queues
Security Scanning
Google App Engine for Go
Go Development Environment
Building App Engine Applications
Writing an HTTP Server
Creating the Configuration File
Testing the Application in Development Server
Deploying App Engine Applications into the Cloud
Creating Hybrid Stand-alone/App Engine applications
Working with Cloud Native Databases
Introduction to Google Cloud Datastore
Entities
Ancestors and Descendants
Working with Cloud Datastore
Creating a New Entity
Querying the Datastore
Running the Application
Building Back-end APIs with Cloud Endpoints
Cloud Endpoints for Go
Installing the endpoints Package
Cloud Endpoints Back-end APIs in Go
Running Cloud Endpoints Back-end API
Generating Client Libraries
Summary
References
Index
THE E XPERT’S VOICE® IN GO Web Development with Go Building Scalable Web Apps and RESTful Services — Shiju Varghese www.it-ebooks.info
Web Development with Go Building Scalable Web Apps and RESTful Services Shiju Varghese www.it-ebooks.info
Web Development with Go Copyright © 2015 by Shiju Varghese This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law. ISBN-13 (pbk): 978-1-4842-1053-6 ISBN-13 (electronic): 978-1-4842-1052-9 Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director: Welmoed Spahr Lead Editor: Celestin John Suresh Technical Reviewer: Prateek Baheti Editorial Board: Steve Anglin, Louise Corrigan, Jim DeWolf, Jonathan Gennick, Robert Hutchinson, Michelle Lowman, James Markham, Susan McDermott, Matthew Moodie, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Gwenan Spearing Coordinating Editor: Jill Balzano Copy Editor: Nancy Sixsmith Compositor: SPi Global Indexer: SPi Global Artist: SPi Global Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springer.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail rights@apress.com, or visit www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this text is available to readers at www.apress.com. For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/. www.it-ebooks.info
I would like to dedicate this book to my parents, the late C.S. Varghese and Rosy Varghese. I would like to thank them for their unconditional love and life struggles for the betterment of our lives. I would like to dedicate this book to my lovely wife Rosmi and beautiful daughter Irene Rose. Without their love and support, this book would not have been possible. Finally, I would like to dedicate this book to my elder sister Shaijy and younger brother Shinto. —Shiju Varghese www.it-ebooks.info
Contents at a Glance About the Author .....................................................................................................xv About the Technical Reviewer ...............................................................................xvii Introduction ............................................................................................................xix ■Chapter 1: Getting Started with Go ........................................................................ 1 ■Chapter 2: Go Fundamentals ............................................................................... 15 ■Chapter 3: User-Defined Types and Concurrency ................................................ 35 ■Chapter 4: Getting Started with Web Development ............................................. 59 ■Chapter 5: Working with Go Templates ............................................................... 79 ■Chapter 6: HTTP Middleware ............................................................................... 99 ■Chapter 7: Authentication to Web Apps ............................................................. 121 ■Chapter 8: Persistence with MongoDB .............................................................. 141 ■Chapter 9: Building RESTful Services ................................................................ 159 ■Chapter 10: Testing Go Applications .................................................................. 211 ■Chapter 11: Building Go Web Applications on Google Cloud ............................. 251 Index ..................................................................................................................... 285 v www.it-ebooks.info
Contents About the Author .....................................................................................................xv About the Technical Reviewer ...............................................................................xvii Introduction ............................................................................................................xix ■Chapter 1: Getting Started with Go ........................................................................ 1 Introducing Go .................................................................................................................. 1 Minimalistic Language with Pragmatic Design ......................................................................................1 A Static Type Language with High Productivity ......................................................................................2 Concurrency Is a Built-In Feature at the Language Level .......................................................................2 Go Compiles Programs Quickly...............................................................................................................3 Go as a General-Purpose Language .......................................................................................................3 Go Ecosystem ................................................................................................................... 4 Installing the Go Tools ...................................................................................................... 4 Checking the Installation ........................................................................................................................6 Setting up a Work Environment ........................................................................................ 7 Go Workspace .........................................................................................................................................7 GOPATH Environment Variable ................................................................................................................7 Code Organization Paths ........................................................................................................................7 Writing Go Programs ........................................................................................................ 8 Writing a Hello World Program ...............................................................................................................8 Writing a Library .....................................................................................................................................9 Testing Go Code ....................................................................................................................................11 Using Go Playground ............................................................................................................................12 vii www.it-ebooks.info
■ CONTENTS Using Go Mobile ............................................................................................................. 13 Go as a Language for Web and Microservices ............................................................... 13 Summary ........................................................................................................................ 14 ■Chapter 2: Go Fundamentals ............................................................................... 15 Packages ........................................................................................................................ 15 Package main .......................................................................................................................................15 Package Alias .......................................................................................................................................16 Function init ..........................................................................................................................................16 Using a Blank Identifier ........................................................................................................................17 Importing Packages ..............................................................................................................................18 Install Third-Party Packages .................................................................................................................18 Writing Packages ..................................................................................................................................19 Go Tool ............................................................................................................................ 21 Formatting Go Code ..............................................................................................................................22 Go Documentation ................................................................................................................................23 Working with Collections ................................................................................................ 24 Arrays ...................................................................................................................................................24 Slices ....................................................................................................................................................25 Maps .....................................................................................................................................................29 Defer, Panic, and Recover ............................................................................................... 31 Defer .....................................................................................................................................................31 Panic .....................................................................................................................................................32 Recover .................................................................................................................................................32 Error Handling ................................................................................................................ 33 Summary ........................................................................................................................ 34 ■Chapter 3: User-Defined Types and Concurrency ................................................ 35 User-defined Types with Structs .................................................................................... 35 Creating a Struct Type ..........................................................................................................................35 Creating Instances of Struct Types .......................................................................................................36 Adding Behavior to a Struct Type ..........................................................................................................37 viii www.it-ebooks.info
■ CONTENTS Type Composition ........................................................................................................... 40 Overriding Methods of Embedded Type .......................................................................... 43 Working with Interfaces ................................................................................................. 44 Concurrency ................................................................................................................... 50 Goroutines ............................................................................................................................................50 GOMAXPROCS and Parallelism .............................................................................................................53 Channels ...............................................................................................................................................54 Summary ........................................................................................................................ 58 ■Chapter 4: Getting Started with Web Development ............................................. 59 net/http Package ............................................................................................................ 59 Processing HTTP Requests ............................................................................................. 60 ServeMux ..............................................................................................................................................61 Handler .................................................................................................................................................61 Building a Static Web Server .......................................................................................... 61 Creating Custom Handlers.............................................................................................. 63 Using Functions as Handlers .......................................................................................... 64 http.HandlerFunc type ..........................................................................................................................64 ServeMux.HandleFunc Function ...........................................................................................................66 DefaultServeMux ............................................................................................................ 66 http.Server Struct ........................................................................................................... 67 Gorilla Mux ..................................................................................................................... 69 Building a RESTful API .................................................................................................... 70 Data Model and Data Store ...................................................................................................................72 Configuring the Multiplexer ..................................................................................................................73 Handler Functions for CRUD Operations ...............................................................................................74 Summary ........................................................................................................................ 77 ix www.it-ebooks.info
分享到:
收藏