Go Building Web Applications 1st Edition Nathan Kozyra Mat Ryer
Go Building Web Applications 1st Edition Nathan Kozyra Mat Ryer
Go Building Web Applications 1st Edition Nathan Kozyra Mat Ryer
Go Building Web Applications 1st Edition Nathan Kozyra Mat Ryer
1. Go Building Web Applications 1st Edition Nathan
Kozyra Mat Ryer download
https://ebookbell.com/product/go-building-web-applications-1st-
edition-nathan-kozyra-mat-ryer-50195586
Explore and download more ebooks at ebookbell.com
2. Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Go Building Web Applications Kozyra Nathanmat Ryer
https://ebookbell.com/product/go-building-web-applications-kozyra-
nathanmat-ryer-11860662
Cloud Native Go Building Web Applications And Microservices For The
Cloud With Go And React 1st Edition Dan Nemeth
https://ebookbell.com/product/cloud-native-go-building-web-
applications-and-microservices-for-the-cloud-with-go-and-react-1st-
edition-dan-nemeth-5655212
Cloud Native Go Building Web Applications And Microservices For The
Cloud With Go And React Dan Nemeth
https://ebookbell.com/product/cloud-native-go-building-web-
applications-and-microservices-for-the-cloud-with-go-and-react-dan-
nemeth-5709616
Web Programming With Go Building And Scaling Interactive Web
Applications With Gos Robust Ecosystem Ian Taylor
https://ebookbell.com/product/web-programming-with-go-building-and-
scaling-interactive-web-applications-with-gos-robust-ecosystem-ian-
taylor-54303326
3. Lets Go Further Advanced Patterns For Building Apis And Web
Applications In Go 110 Alex Edwards
https://ebookbell.com/product/lets-go-further-advanced-patterns-for-
building-apis-and-web-applications-in-go-110-alex-edwards-38438846
Building Distributed Applications In Gin A Handson Guide For Go
Developers To Build And Deploy Distributed Web Apps With The Gin
Framework Mohamed Labouardy
https://ebookbell.com/product/building-distributed-applications-in-
gin-a-handson-guide-for-go-developers-to-build-and-deploy-distributed-
web-apps-with-the-gin-framework-mohamed-labouardy-35015480
Web Development With Go Building Scalable Web Apps And Restful
Services 1st Ed 2015 Shiju Varghese
https://ebookbell.com/product/web-development-with-go-building-
scalable-web-apps-and-restful-services-1st-ed-2015-shiju-
varghese-5299546
Building Restful Web Services With Go Learn How To Build Powerful
Restful Apis With Golang That Scale Gracefully 1st Edition Naren
Yellavula
https://ebookbell.com/product/building-restful-web-services-with-go-
learn-how-to-build-powerful-restful-apis-with-golang-that-scale-
gracefully-1st-edition-naren-yellavula-52767254
Building Restful Web Services With Go Naren Yellavula
https://ebookbell.com/product/building-restful-web-services-with-go-
naren-yellavula-230435390
6. Table of Contents
Go: Building Web Applications
Go: Building Web Applications
Credits
Preface
What this learning path covers
What you need for this learning path
Who this learning path is for
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Module 1
1. Introducing and Setting Up Go
Installing Go
Structuring a project
Code conventions
Importing packages
Handling private repositories
Dealing with versioning
Introducing the net package
Hello, Web
Summary
2. Serving and Routing
Serving files directly
Basic routing
Using more complex routing with Gorilla
Redirecting requests
Serving basic errors
Summary
3. Connecting to Data
Connecting to a database
7. Creating a MySQL database
Using GUID for prettier URLs
Handling 404s
Summary
4. Using Templates
Introducing templates, context, and visibility
HTML templates and text templates
Displaying variables and security
Using logic and control structures
Summary
5. Frontend Integration with RESTful APIs
Setting up the basic API endpoint
RESTful architecture and best practices
Creating our first API endpoint
Implementing security
Creating data with POST
Modifying data with PUT
Summary
6. Sessions and Cookies
Setting cookies
Capturing user information
Creating users
Enabling sessions
Letting users register
Letting users log in
Initiating a server-side session
Creating a store
Utilizing flash messages
Summary
7. Microservices and Communication
Introducing the microservice approach
Pros and cons of utilizing microservices
Understanding the heart of microservices
Communicating between microservices
Putting a message on the wire
Reading from another service
Summary
8. 8. Logging and Testing
Introducing logging in Go
Logging to IO
Multiple loggers
Formatting your output
Using panics and fatal errors
Introducing testing in Go
Summary
9. Security
HTTPS everywhere – implementing TLS
Preventing SQL injection
Protecting against XSS
Preventing cross-site request forgery (CSRF)
Securing cookies
Using the secure middleware
Summary
10. Caching, Proxies and Improved Performance
Identifying bottlenecks
Implementing reverse proxies
Implementing caching strategies
Using Least Recently Used
Caching by file
Caching in memory
Implementing HTTP/2
Summary
2. Module 2
1. Chat Application with Web Sockets
A simple web server
Templates
Doing things once
Using your own handlers
Properly building and executing Go programs
Modeling a chat room and clients on the server
Modeling the client
Modeling a room
Concurrency programming using idiomatic Go
Turning a room into an HTTP handler
9. Use helper functions to remove complexity
Creating and using rooms
Building an HTML and JavaScript chat client
Getting more out of templates
Tracing code to get a look under the hood
Writing a package using TDD
Interfaces
Unit tests
Red-green testing
Implementing the interface
Unexported types being returned to users
Using our new trace package
Making tracing optional
Clean package APIs
Summary
2. Adding Authentication
Handlers all the way down
Making a pretty social sign-in page
Endpoints with dynamic paths
OAuth2
Open source OAuth2 packages
Tell the authentication providers about your app
Implementing external logging in
Logging in
Handling the response from the provider
Presenting the user data
Augmenting messages with additional data
Summary
3. Three Ways to Implement Profile Pictures
Avatars from the authentication server
Getting the avatar URL
Transmitting the avatar URL
Adding the avatar to the user interface
Logging out
Making things prettier
Implementing Gravatar
Abstracting the avatar URL process
10. The authentication service and avatar's implementation
Using an implementation
Gravatar implementation
Uploading an avatar picture
User identification
An upload form
Handling the upload
Serving the images
The Avatar implementation for local files
Supporting different file types
Refactoring and optimizing our code
Replacing concrete types with interfaces
Changing interfaces in a test-driven way
Fixing existing implementations
Global variables versus fields
Implementing our new design
Tidying up and testing
Combining all three implementations
Summary
4. Command-line Tools to Find Domain Names
Pipe design for command-line tools
Five simple programs
Sprinkle
Exercise – configurable transformations
Domainify
Exercise – making top-level domains configurable
Coolify
Synonyms
Using environment variables for configuration
Consuming a web API
Getting domain suggestions
Available
Composing all five programs
One program to rule them all
Summary
5. Building Distributed Systems and Working with Flexible Data
System design
11. Database design
Installing the environment
NSQ
NSQ driver for Go
MongoDB
MongoDB driver for Go
Starting the environment
Votes from Twitter
Authorization with Twitter
Extracting the connection
Reading environment variables
Reading from MongoDB
Reading from Twitter
Signal channels
Publishing to NSQ
Gracefully starting and stopping
Testing
Counting votes
Connecting to the database
Consuming messages in NSQ
Keeping the database updated
Responding to Ctrl + C
Running our solution
Summary
6. Exposing Data and Functionality through a RESTful Data Web
Service API
RESTful API design
Sharing data between handlers
Wrapping handler functions
API key
Database session
Per request variables
Cross-browser resource sharing
Responding
Understanding the request
A simple main function to serve our API
Using handler function wrappers
12. Handling endpoints
Using tags to add metadata to structs
Many operations with a single handler
Reading polls
Creating a poll
Deleting a poll
CORS support
Testing our API using curl
A web client that consumes the API
An index page showing a list of polls
A page to create a new poll
A page to show details of the poll
Running the solution
Summary
7. Random Recommendations Web Service
Project overview
Project design specifics
Representing data in code
Public views of Go structs
Generating random recommendations
Google Places API key
Enumerators in Go
Test-driven enumerator
Querying the Google Places API
Building recommendations
Handlers that use query parameters
CORS
Testing our API
Web application
Summary
8. Filesystem Backup
Solution design
Project structure
Backup package
Obvious interfaces?
Implementing ZIP
Has the filesystem changed?
13. Checking for changes and initiating a backup
Hardcoding is OK for a short while
The user command-line tool
Persisting small data
Parsing arguments
Listing the paths
String representations for your own types
Adding paths
Removing paths
Using our new tool
The daemon backup tool
Duplicated structures
Caching data
Infinite loops
Updating filedb records
Testing our solution
Summary
3. Module 3
1. An Introduction to Concurrency in Go
Introducing goroutines
A patient goroutine
Implementing the defer control mechanism
Using Go's scheduler
Using system variables
Understanding goroutines versus coroutines
Implementing channels
Channel-based sorting at the letter capitalization factory
Cleaning up our goroutines
Buffered or unbuffered channels
Using the select statement
Closures and goroutines
Building a web spider using goroutines and channels
Summary
2. Understanding the Concurrency Model
Understanding the working of goroutines
Synchronous versus asynchronous goroutines
Designing the web server plan
14. Visualizing concurrency
RSS in action
An RSS reader with self diagnostics
Imposing a timeout
A little bit about CSP
The dining philosophers problem
Go and the actor model
Object orientation
Demonstrating simple polymorphism in Go
Using concurrency
Managing threads
Using sync and mutexes to lock data
Summary
3. Developing a Concurrent Strategy
Applying efficiency in complex concurrency
Identifying race conditions with race detection
Using mutual exclusions
Exploring timeouts
Importance of consistency
Synchronizing our concurrent operations
The project – multiuser appointment calendar
Visualizing a concurrent pattern
Developing our server requirements
Web server
The Gorilla toolkit
Using templates
Time
Endpoints
Custom structs
A multiuser Appointments Calendar
A note on style
A note on immutability
Summary
4. Data Integrity in an Application
Getting deeper with mutexes and sync
The cost of goroutines
Working with files
15. Getting low – implementing C
Touching memory in cgo
The structure of cgo
The other way around
Getting even lower – assembly in Go
Distributed Go
Some common consistency models
Distributed shared memory
First-in-first-out – PRAM
Looking at the master-slave model
The producer-consumer problem
Looking at the leader-follower model
Atomic consistency / mutual exclusion
Release consistency
Using memcached
Circuit
Summary
5. Locks, Blocks, and Better Channels
Understanding blocking methods in Go
Blocking method 1 – a listening, waiting channel
Sending more data types via channels
Creating a function channel
Using an interface channel
Using structs, interfaces, and more complex channels
The net package – a chat server with interfaced channels
Handling direct messages
Examining our client
Blocking method 2 – the select statement in a loop
Cleaning up goroutines
Blocking method 3 – network connections and reads
Creating channels of channels
Pprof – yet another awesome tool
Handling deadlocks and errors
Summary
6. C10K – A Non-blocking Web Server in Go
Attacking the C10K problem
Failing of servers at 10,000 concurrent connections
16. Using concurrency to attack C10K
Taking another approach
Building our C10K web server
Benchmarking against a blocking web server
Handling requests
Routing requests
Serving pages
Parsing our template
External dependencies
Connecting to MySQL
Multithreading and leveraging multiple cores
Exploring our web server
Timing out and moving on
Summary
7. Performance and Scalability
High performance in Go
Getting deeper into pprof
Parallelism's and concurrency's impact on I/O pprof
Using the App Engine
Distributed Go
Types of topologies
Type 1 – star
Type 2 – mesh
The Publish and Subscribe model
Serialized data
Remote code execution
Other topologies
Message Passing Interface
Some helpful libraries
Nitro profiler
Heka
GoFlow
Memory preservation
Garbage collection in Go
Summary
8. Concurrent Application Architecture
Designing our concurrent application
17. Identifying our requirements
Using NoSQL as a data store in Go
MongoDB
Redis
Tiedot
CouchDB
Cassandra
Couchbase
Setting up our data store
Monitoring filesystem changes
Managing logfiles
Handling configuration files
Detecting file changes
Sending changes to clients
Checking records against Couchbase
Backing up our files
Designing our web interface
Reverting a file's history – command line
Using Go in daemons and as a service
Checking the health of our server
Summary
9. Logging and Testing Concurrency in Go
Handling errors and logging
Breaking out goroutine logs
Using the LiteIDE for richer and easier debugging
Sending errors to screen
Logging errors to file
Logging errors to memory
Using the log4go package for robust logging
Panicking
Recovering
Logging our panics
Catching stack traces with concurrent code
Using the runtime package for granular stack traces
Summary
10. Advanced Concurrency and Best Practices
Going beyond the basics with channels
18. Building workers
Implementing nil channel blocks
Using nil channels
Implementing more granular control over goroutines with tomb
Timing out with channels
Building a load balancer with concurrent patterns
Choosing unidirectional and bidirectional channels
Using receive-only or send-only channels
Using an indeterminate channel type
Using Go with unit testing
GoCheck
Ginkgo and Gomega
Using Google App Engine
Utilizing best practices
Structuring your code
Documenting your code
Making your code available via go get
Keeping concurrency out of your packages
Summary
A. Bibliography
Index
20. Go: Building Web Applications
Build real-world, production-ready solutions by harnessing the powerful
features of Go
A course in three modules
BIRMINGHAM - MUMBAI
22. Credits
Authors
Nathan Kozyra
Mat Ryer
Reviewers
Karthik Nayak
Tyler Bunnell
Michael Hamrah
Nimish Parmar
Jeremy R. Budnack
János Fehér
Aleksandar S. Sokolovski
Michele Della Torre
Content Development Editor
Arun Nadar
Graphics
Abhinash Sahu
Production Coordinator
Melwyn D'sa
23. Preface
Since the late 1980s and early 1990s, there has been a slow flood of
powerful new languages and paradigms—Perl, Python, Ruby, PHP, and
JavaScript—have taken an expanding user base by storm and has
become one of the most popular languages (up there with stalwarts such
as C, C++, and Java). Multithreading, memory caching, and APIs have
allowed multiple processes, dissonant languages, applications, and even
separate operating systems to work in congress.
And while this is great, there's a niche that until very recently was largely
unserved: powerful, compiled, cross-platform languages with
concurrency support that are geared towards systems programmers.
So when Google announced Go in 2009, which included some of the
best minds in language design (and programming in general)—Rob Pike
and Ken Thompson of Bell Labs fame and Robert Griesemer, who
worked on Google's JavaScript implementation V8—to design a modern,
concurrent language with development ease at the forefront.
For Go programming bright future, the team focused on some sore spots
in the alternatives, which are as follows:
Dynamically typed languages have—in recent years—become
incredibly popular. Go eschews the explicit, "cumbersome" type
systems of Java or C++. Go uses type inference, which saves
development time, but is still also strongly typed.
Concurrency, parallelism, pointers/memory access, and garbage
collection are unwieldy in the aforementioned languages. Go lets
these concepts be as easy or as complicated as you want or need
them to be.
As a newer language, Go has a focus on multicore design that was a
necessary afterthought in languages such as C++.
Go's compiler is super-fast; it's so fast that there are
implementations of it that treat Go code as interpreted.
Although Google designed Go to be a systems language, it's
versatile enough to be used in a myriad of ways. Certainly, the focus
24. on advanced, cheap concurrency makes it ideal for network and
systems programming.
Go is loose with syntax, but strict with usage. By this we mean that
Go will let you get a little lazy with some lexer tokens, but you still
have to produce fundamentally tight code. As Go provides a
formatting tool that attempts to clarify your code, you can also spend
less time on readability concerns as you're coding
What this learning path covers
Module 1, Learning Go Web Development, starts off with introducing and
setting up Go before you move on to produce responsive servers that
react to certain web endpoint. You will then implement database
connections to acquire data and then present it to our users using
different template packages. Later on, you will learn about sessions and
cookies to retain information before delving with the basics of
microservices. By the end of this module, we will be covering the testing,
debugging, and the security aspect.
Module 2, Go Programming Blueprints, has a project-based approach
where you will be building chat application, adding authentication, and
adding your own profile pictures in different ways. You will learn how Go
makes it easy to build powerful command-line tools to find domain names
before building a highly scalable Twitter polling and vote counting engine
powered by NSQ and MongoDB. Later on it covers the functionalities of
RESTful Data Web Service API and Google Places API before you move
on to build a simple but powerful filesystem backup tool for our code
projects.
Module 3, Mastering Concurrency in Go, introduces you to Concurrency
in Go where you will be understanding the Concurrency model and
developing a strategy for designing applications. You will learn to create
basic and complex communication channels between our goroutines to
manage data not only across single or multithreaded systems but also
distributed systems. Later on you will be tackling a real-world problem,
that is, being able to develop a high performance web server that can
25. handle a very large volume of live, active traffic. You will then learn how
to scale your application and make it capable of being expanded in
scope, design, and/or capacity. It will then focus on when and where to
implement concurrent patterns, utilize parallelism, and ensure data
consistency. At the end of this module, we will be logging and testing
concurrency before we finally look at the best practices on how to
implement complicated and advanced techniques offered by Go.
26. What you need for this learning
path
For this course, any modern computers running a standard Linux flavor,
OS X or Windows should be enough to get started. You can find a full list
of requirements at https://golang.org/dl/. Later on, you'll also need to
have the following software installed:
MySQL (http://dev.mysql.com/downloads/)
Couchbase (http://www.couchbase.com/download)
Your choice of IDE is a matter of personal preference.
27. Who this learning path is for
This course is intended for developers who are new to Go but have
previous experience of building web applications and APIs. It is also
targeted towards systems or network programmer with some knowledge
of Go and concurrency, but would like to know about the implementation
of concurrent systems written in Go
28. 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 <feedback@packtpub.com>,
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 book, see our author guide at
www.packtpub.com/authors.
29. 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 emailed 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
30. The code bundle for the course is also hosted on GitHub at
https://github.com/PacktPublishing/repository-name. 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.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem
across all media. At Packt, we take the protection of our copyright and
licenses very seriously. If you come across any illegal copies of our
works in any form on the Internet, please provide us with the location
address or website name immediately so that we can pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the
suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring
you valuable content.
31. Questions
If you have a problem with any aspect of this course, you can contact us
at <questions@packtpub.com>, and we will do our best to address the
problem.
32. Part 1. Module 1
Learning Go Web Development
Build frontend-to-backend web applications using the best practices of a
powerful, fast, and easy-to-deploy server language
33. Chapter 1. Introducing and
Setting Up Go
When starting with Go, one of the most common things you'll hear being
said is that it's a systems language.
Indeed, one of the earlier descriptions of Go, by the Go team itself, was
that the language was built to be a modern systems language. It was
constructed to combine the speed and power of languages, such as C
with the syntactical elegance and thrift of modern interpreted languages,
such as Python. You can see that goal realized when you look at just a
few snippets of Go code.
From the Go FAQ on why Go was created:
"Go was born out of frustration with existing languages and environments
for systems programming."
Perhaps the largest part of present-day Systems programming is
designing backend servers. Obviously, the Web comprises a huge, but
not exclusive, percentage of that world.
Go hasn't been considered a web language until recently. Unsurprisingly,
it took a few years of developers dabbling, experimenting, and finally
embracing the language to start taking it to new avenues.
While Go is web-ready out of the box, it lacks a lot of the critical
frameworks and tools people so often take for granted with web
development now. As the community around Go grew, the scaffolding
began to manifest in a lot of new and exciting ways. Combined with
existing ancillary tools, Go is now a wholly viable option for end-to-end
web development. But back to that primary question: Why Go? To be fair,
it's not right for every web project, but any application that can benefit
from high-performance, secure web-serving out of the box with the added
benefits of a beautiful concurrency model would make for a good
34. benefits of a beautiful concurrency model would make for a good
candidate.
In this book, we're going to explore those aspects and others to outline
what can make Go the right language for your web architecture and
applications.
We're not going to deal with a lot of the low-level aspects of the Go
language. For example, we assume you're familiar with variable and
constant declaration. We assume you understand control structures.
In this chapter we will cover the following topics:
Installing Go
Structuring a project
Importing packages
Introducing the net package
Hello, Web
Installing Go
The most critical first step is, of course, making sure that Go is available
and ready to start our first web server.
Note
While one of Go's biggest selling points is its cross-platform support
(both building and using locally while targeting other operating
systems), your life will be much easier on a Nix compatible platform.
If you're on Windows, don't fear. Natively, you may run into
incompatible packages, firewall issues when running using go run
command and some other quirks, but 95% of the Go ecosystem will
be available to you. You can also, very easily, run a virtual machine,
and in fact that is a great way to simulate a potential production
environment.
35. In-depth installation instructions are available at
https://golang.org/doc/install, but we'll talk about a few quirky points here
before moving on.
For OS X and Windows, Go is provided as a part of a binary installation
package. For any Linux platform with a package manager, things can be
pretty easy.
Note
To install via common Linux package managers:
Ubuntu: sudo apt-get golang
CentOS: sudo yum install golang
On both OS X and Linux, you'll need to add a couple of lines to your path
—the GOPATH and PATH. First, you'll want to find the location of your Go
binary's installation. This varies from distribution to distribution. Once
you've found that, you can configure the PATH and GOPATH, as follows:
export PATH=$PATH:usrlocal/go/bin
export GOPATH="usrshare/go"
While the path to be used is not defined rigidly, some convention has
coalesced around starting at a subdirectory directly under your user's
home directory, such as $HOME/go or ~Home/go. As long as this location is
set perpetually and doesn't change, you won't run into issues with
conflicts or missing packages.
You can test the impact of these changes by running the go env
command. If you see any issues with this, it means that your directories
are not correct.
Note that this may not prevent Go from running—depending on whether
the GOBIN directory is properly set—but will prevent you from installing
packages globally across your system.
36. To test the installation, you can grab any Go package by a go get
command and create a Go file somewhere. As a quick example, first get
a package at random, we'll use a package from the Gorilla framework, as
we'll use this quite a bit throughout this book.
go get github.com/gorilla/mux
If this runs without any issue, Go is finding your GOPATH correctly. To
make sure that Go is able to access your downloaded packages, draw up
a very quick package that will attempt to utilize Gorilla's mux package
and run it to verify whether the packages are found.
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
func TestHandler(w http.ResponseWriter, r
*http.Request) {
}
func main() {
router := mux.NewRouter()
router.HandleFunc("test", TestHandler)
http.Handle("", router)
fmt.Println("Everything is set up!")
}
Run go run test.go in the command line. It won't do much, but it will
deliver the good news as shown in the following screenshot:
37. Structuring a project
When you're first getting started and mostly playing around, there's no
real problem with setting your application lazily.
For example, to get started as quickly as possible, you can create a
simple hello.go file anywhere you like and compile without issue.
But when you get into environments that require multiple or distinct
packages (more on that shortly) or have more explicit cross-platform
requirements, it makes sense to design your project in a way that will
facilitate the use of the go build tool.
The value of setting up your code in this manner lies in the way that the
go build tool works. If you have local (to your project) packages, the build
tool will look in the src directory first and then your GOPATH. When you're
building for other platforms, go build will utilize the local bin folder to
organize the binaries.
When building packages that are intended for mass use, you may also
find that either starting your application under your GOPATH directory and
then symbolically linking it to another directory, or doing the opposite, will
allow you to develop without the need to subsequently go get your own
code.
Code conventions
As with any language, being a part of the Go community means
perpetual consideration of the way others create their code. Particularly if
you're going to work in open source repositories, you'll want to generate
your code the way that others do, in order to reduce the amount of friction
when people get or include your code.
One incredibly helpful piece of tooling that the Go team has included is
go fmt. fmt here, of course, means format and that's exactly what this tool
does, it automatically formats your code according to the designed
38. conventions.
By enforcing style conventions, the Go team has helped to mitigate one
of the most common and pervasive debates that exist among a lot of
other languages.
While the language communities tend to drive coding conventions, there
are always little idiosyncrasies in the way individuals write programs.
Let's use one of the most common examples around—where to put the
opening bracket.
Some programmers like it on the same line as the statement:
for (int i = 0; i < 100; i++) {
// do something
}
While others prefer it on the subsequent line:
for (int i = 0; i < 100; i++)
{
// do something
}
These types of minor differences spark major, near-religious debates.
The Gofmt tool helps alleviate this by allowing you to yield to Go's
directive.
Now, Go bypasses this obvious source of contention at the compiler, by
formatting your code similar to the latter example discussed earlier. The
compiler will complain and all you'll get is a fatal error. But the other style
choices have some flexibility, which are enforced when you use the tool
to format.
Here, for example, is a piece of code in Go before go fmt:
func Double(n int) int {
if (n == 0) {
39. return 0
} else {
return n * 2
}
}
Arbitrary whitespace can be the bane of a team's existence when it
comes to sharing and reading code, particularly when every team
member is not on the same IDE.
By running go fmt, we clean this up, thereby translating our whitespace
according to Go's conventions:
func Double(n int) int {
if n == 0 {
return 0
} else {
return n * 2
}
}
Long story short: always run go fmt before shipping or pushing your
code.
40. Importing packages
Beyond the absolute and the most trivial application—one that cannot
even produce a Hello World output—you must have some imported
package in a Go application.
To say Hello World, for example, we'd need some sort of a way to
generate an output. Unlike in many other languages, even the core
language library is accessible by a namespaced package. In Go,
namespaces are handled by a repository endpoint URL, which is
github.com/nkozyra/gotest, which can be opened directly on GitHub (or
any other public location) for the review.
Handling private repositories
The go get tool easily handles packages hosted at the repositories, such
as GitHub, Bitbucket, and Google Code (as well as a few others). You
can also host your own projects, ideally a git project, elsewhere, although
it might introduce some dependencies and sources for errors, which
you'd probably like to avoid.
But what about the private repos? While go get is a wonderful tool, you'll
find yourself looking at an error without some additional configuration,
SSH agent forwarding, and so on.
You can work around this in a couple of ways, but one very simple
method is to clone the repository locally, using your version control
software directly.
Dealing with versioning
You may have paused when you read about the way namespaces are
defined and imported in a Go application. What happens if you're using
version 1 of the application but would like to bring in version 2? In most
cases, this has to be explicitly defined in the path of the import. For
example:
41. import (
"github.com/foo/foo-v1"
)
versus:
import (
"github.com/foo/foo-v2"
)
As you might imagine, this can be a particularly sticky aspect of the way
Go handles the remote packages.
Unlike a lot of other package managers, go get is decentralized—that is,
nobody maintains a canonical reference library of packages and
versions. This can sometimes be a sore spot for new developers.
For the most part, packages are always imported via the go get
command, which reads the master branch of the remote repository. This
means that maintaining multiple versions of a package at the same
endpoint is, for the most part, impossible.
It's the utilization of the URL endpoints as namespaces that allows the
decentralization, but it's also what provides a lack of internal support for
versioning.
Your best bet as a developer is to treat every package as the most up-to-
date version when you perform a go get command. If you need a newer
version, you can always follow whatever pattern the author has decided
on, such as the preceding example.
As a creator of your own packages, make sure that you also adhere to
this philosophy. Keeping your master branch HEAD as the most up-to-
date will make sure your that the code fits with the conventions of other
Go authors.
42. Introducing the net package
At the heart of all network communications in Go is the aptly-named net
package, which contains subpackages not only for the very relevant
HTTP operations, but also for other TCP/UDP servers, DNS, and IP
tools.
In short, everything you need to create a robust server environment.
Of course, what we care about for the purpose of this book lies primarily
in the net/http package, but we'll look at a few other functions that utilize
the rest of the package, such as a TCP connection, as well as
WebSockets.
Let's quickly take a look at just performing that Hello World (or Web, in
this case) example we have been talking about.
43. Hello, Web
The following application serves as a static file at the location /static,
and a dynamic response at the location /dynamic:
package main
import (
"fmt"
"net/http"
"time"
)
const (
Port = ":8080"
)
func serveDynamic(w http.ResponseWriter, r
*http.Request) {
response := "The time is now " + time.Now().String()
fmt.Fprintln(w,response)
}
Just as fmt.Println will produce desired content at the console level,
Fprintln allows you to direct output to any writer. We'll talk a bit more
about the writers in Chapter 2, Serving and Routing, but they represent a
fundamental, flexible interface that is utilized in many Go applications, not
just for the Web:
func serveStatic(w http.ResponseWriter, r
*http.Request) {
http.ServeFile(w, r, "static.html")
}
Our serveStatic method just serves one file, but it's trivial to allow it to
serve any file directly and use Go as an old-school web server that
serves only static content:
func main() {
http.HandleFunc("static",serveStatic)
44. http.HandleFunc("",serveDynamic)
http.ListenAndServe(Port,nil)
}
Feel free to choose the available port of your choice—higher ports will
make it easier to bypass the built-in security functionality, particularly in
Nix systems.
If we take the preceding example and visit the respective URLs—in this
case the root at / and a static page at /static, we should see the
intended output as shown:
At the root, / , the output is as follows:
At /static, the output is as follows:
As you can see, producing a very simple output for the Web is, well, very
simple in Go. The built-in package allows us to create a basic, yet
inordinately fast site in Go with just a few lines of code using native
packages.
45. This may not be very exciting, but before we can run, we must walk.
Producing the preceding output introduces a few key concepts.
First, we've seen how net/http directs requests using a URI or URL
endpoint to helper functions, which must implement the
http.ResponseWriter and http.Request methods. If they do not implement
it, we get a very clear error on that end.
The following is an example that attempts to implement it in this manner:
func serveError() {
fmt.Println("There's no way I'll work!")
}
func main() {
http.HandleFunc("static", serveStatic)
http.HandleFunc("", serveDynamic)
http.HandleFunc("/error",serveError)
http.ListenAndServe(Port, nil)
}
The following screenshot shows the resulting error you'll get from Go:
You can see that serveError does not include the required parameters
and thus results in a compilation error.
46. Summary
This chapter serves as an introduction to the most basic concepts of Go
and producing for the Web in Go, but these points are critical
foundational elements for being productive in the language and in the
community.
We've looked at coding conventions and package design and
organization, and we've produced our first program—the all-too-familiar
Hello, World application—and accessed it via our localhost.
Obviously, we're a long way from a real, mature application for the Web,
but the building blocks are essential to getting there.
In Chapter 2, Serving and Routing, we'll look at how to direct different
requests to different application logic using the built-in routing
functionality in Go's net/http package, as well as a couple of third party
router packages.
47. Chapter 2. Serving and Routing
The cornerstone of the Web as a commercial entity—the piece on which
marketing and branding has relied on nearly exclusively—is the URL.
While we're not yet looking at the top-level domain handling, we need to
take up the reins of our URL and its paths (or endpoints).
In this chapter, we'll do just this by introducing multiple routes and
corresponding handlers. First, we'll do this with a simple flat file serving
and then we'll introduce complex mixers to do the routing with more
flexibility by implementing a library that utilizes regular expressions in its
routes.
By the end of this chapter, you should be able to create a site on
localhost that can be accessed by any number of paths and return
content relative to the requested path.
In this chapter, we will cover the following topics:
Serving files directly
Basic routing
Using more complex routing with Gorilla
Redirecting requests
Serving basic errors
Serving files directly
In the preceding chapter, we utilized the fmt.Fprintln function to output
some generic Hello, World messaging in the browser.
This obviously has limited utility. In the earliest days of the Web and web
servers, the entirety of the Web was served by directing requests to
corresponding static files. In other words, if a user requested home.html,
the web server would look for a file called home.html and return it to the
user.
48. This might seem quaint today, as a vast majority of the Web is now
served in some dynamic fashion, with content often being determined via
database IDs, which allows for pages to be generated and regenerated
without someone modifying the individual files.
Let's take a look at the simplest way in which we can serve files in a way
similar to those olden days of the Web as shown:
package main
import (
"net/http"
)
const (
PORT = ":8080"
)
func main() {
http.ListenAndServe(PORT,
http.FileServer(http.Dir("varwww")))
}
Pretty simple, huh? Any requests made to the site will attempt to find a
corresponding file in our local varwww directory. But while this has a more
practical use compared to the example in Chapter 1, Introducing and
Setting Up Go, it's still pretty limited. Let's take a look at expanding our
options a bit.
49. Basic routing
In Chapter 1, Introducing and Setting Up, we produced a very basic URL
endpoint that allowed static file serving.
The following are the simple routes we produced for that example:
func main() {
http.HandleFunc("static",serveStatic)
http.HandleFunc("",serveDynamic)
http.ListenAndServe(Port,nil)
}
In review, you can see two endpoints, /static and /, which either serve a
single static file or generate output to the http.ResponseWriter.
We can have any number of routers sitting side by side. However,
consider a scenario where we have a basic website with about, contact,
and staff pages, with each residing in varwww/about/index.html,
varwww/contact.html, and varwww/staff/home.html. While it's an
intentionally obtuse example, it demonstrates the limitations of Go's built-
in and unmodified routing system. We cannot route all requests to the
same directory locally, we need something that provides more malleable
URLs.
50. Using more complex routing with
Gorilla
In the previous session, we looked at basic routing but that can only take
us so far, we have to explicitly define our endpoints and then assign them
to handlers. What happens if we have a wildcard or a variable in our
URL? This is an absolutely essential part of the Web and any serious
web server.
To invoke a very simple example, consider hosting a blog with unique
identifiers for each blog entry. This could be a numeric ID representing a
database ID entry or a text-based globally unique identifier, such as my-
first-block-entry.
Note
In the preceding example, we want to route a URL like pages1 to a
filename called 1.html. Alternately, in a database-based scenario,
we'd want to use pages1 or pageshello-world to map to a database
entry with a GUID of 1 or hello-world, respectively. To do this we
either need to include an exhaustive list of possible endpoints, which
is extremely wasteful, or implement wildcards, ideally through regular
expressions.
In either case, we'd like to be able to utilize the value from the URL
directly within our application. This is simple with URL parameters from
GET or POST. We can extract those simply, but they aren't particularly
elegant in terms of clean, hierarchical or descriptive URLs that are often
necessary for search engine optimization purposes.
The built-in net/http routing system is, perhaps by design, relatively
simple. To get anything more complicated out of the values in any given
request, we either need to extend the routing capabilities or use a
package that has done this.
51. In the few years that Go has been publicly available and the community
has been growing, a number of web frameworks have popped up. We'll
talk about these in a little more depth as we continue the book, but one in
particular is well-received and very useful: the Gorilla web toolkit.
As the name implies, Gorilla is less of a framework and more of a set of
very useful tools that are generally bundled in frameworks. Specifically,
Gorilla contains:
gorilla/context: This is a package for creating a globally-accessible
variable from the request. It's useful for sharing a value from the
URL without repeating the code to access it across your application.
gorilla/rpc: This implements RPC-JSON, which is a system for
remote code services and communication without implementing
specific protocols. This relies on the JSON format to define the
intentions of any request.
gorilla/schema: This is a package that allows simple packing of form
variables into a struct, which is an otherwise cumbersome process.
gorilla/securecookie: This, unsurprisingly, implements
authenticated and encrypted cookies for your application.
gorilla/sessions: Similar to cookies, this provides unique, long-
term, and repeatable data stores by utilizing a file-based and/or
cookie-based session system.
gorilla/mux: This is intended to create flexible routes that allow
regular expressions to dictate available variables for routers.
The last package is the one we're most interested in here, and it
comes with a related package called gorilla/reverse, which
essentially allows you to reverse the process of creating regular
expression-based muxes. We will cover that topic in detail in the
later section.
Note
You can grab individual Gorilla packages by their GitHub location with
a go get. For example, to get the mux package, going to
github.com/gorilla/mux will suffice and bring the package into your
GOPATH. For the locations of the other packages (they're fairly self-
52. explanatory), visit http://www.gorillatoolkit.org/
Let's dive-in and take a look at how to create a route that's flexible and
uses a regular expression to pass a parameter to our handler:
package main
import (
"github.com/gorilla/mux"
"net/http"
)
const (
PORT = ":8080"
)
This should look familiar to our last code with the exception of the Gorilla
package import:
func pageHandler(w http.ResponseWriter, r
*http.Request) {
vars := mux.Vars(r)
pageID := vars["id"]
fileName := "files/" + pageID + ".html"
http.ServeFile(w,r,fileName)
}
Here, we've created a route handler to accept the response. The thing to
be noted here is the use of mux.Vars, which is a method that will look for
query string variables from the http.Request and parse them into a map.
The values will then be accessible by referencing the result by key, in this
case id, which we'll cover in the next section.
func main() {
rtr := mux.NewRouter()
rtr.HandleFunc("pages{id:[0-9]+}",pageHandler)
http.Handle("/",rtr)
http.ListenAndServe(PORT,nil)
}
53. Here, we can see a (very basic) regular expression in the handler. We're
assigning any number of digits after pages to a parameter named id in
{id:[0-9]+}; this is the value we pluck out in pageHandler.
A simpler version that shows how this can be used to delineate separate
pages can be seen by adding a couple of dummy endpoints:
func main() {
rtr := mux.NewRouter()
rtr.HandleFunc("pages{id:[0-9]+}", pageHandler)
rtr.HandleFunc("homepage", pageHandler)
rtr.HandleFunc("contact", pageHandler)
http.Handle("/", rtr)
http.ListenAndServe(PORT, nil)
}
When we visit a URL that matches this pattern, our pageHandler attempts
to find the page in the files/ subdirectory and returns that file directly.
A response to pages1 would look like this:
At this point, you might already be asking, but what if we don't have the
requested page? Or, what happens if we've moved that location? This
brings us to two important mechanisms in web serving—returning error
responses and, as part of that, potentially redirecting requests that have
moved or have other interesting properties that need to be reported back
56. Illi robur et æs triplex
Circa pectus erat.
To see the convulsions, agonies, and tortures of a poor
fellow-creature, whom they cannot restore nor recompense,
dying to gratify luxury, and tickle callous and rank organs,
must require a rocky heart, and a great degree of cruelty and
ferocity. I cannot find any great difference, on the foot of
natural reason and equity only, between feeding on human
flesh and feeding on brute animal flesh, except custom and
example.
I believe some [more] rational creatures would suffer less
in being fairly butchered than a strong Ox or red Deer; and,
in natural morality and justice, the degrees of pain here make
the essential difference, for as to other differences, they are
relative only, and can be of no influence with an infinitely
perfect Being. Did not use and example weaken this lesson,
and make the difference, reason alone could never do it.”—
Essay on Regimen, &c. 8vo. 1740. Pages 54 and 70.
Noble and courageous words! Courageous as
coming from an eminent member of a profession—
which almost rivals the legal or even the clerical, in
opposition to all change in the established order of
things. In Dr. Cheyne’s days such interested or
bigoted opposition was even stronger than in the
present time. From the period of the final
establishment of his health, about 1728, little is
known of his life excepting through his writings.
Almost all we know is, that he continued some
fifteen years to practise in London and in Bath with
57. distinguished reputation and success. He had
married a daughter of Dr. Middleton of Bristol by
whom he had several children. His only son was born
in 1712. Amongst his intimate friends was the
celebrated Dr. Arbuthnot, a Scotchman like himself,
and we find him meeting Sir Hans Sloane and Dr.
Mead at the bedside of his friend and relative Bishop
Burnet. Both Dr. Arbuthnot and Sir Hans Sloane, we
may remark in passing, have given evidence in
favour of the purer living. His own diet he thus
describes in his Author’s Case, written towards the
end of his life:—
“My regimen, at present, is milk, with tea, coffee, bread
and butter, mild cheese, salads, fruits and seeds of all kinds,
with tender roots (as potatoes, turnips, carrots), and, in
short, everything that has not life, dressed or not, as I like it,
in which there is as much or a greater variety than in animal
foods, so that the stomach need never be cloyed. I drink no
wine nor any fermented liquors, and am rarely dry, most of
my food being liquid, moist, or juicy.[141] Only after dinner I
drink either coffee or green tea, but seldom both in the same
day, and sometimes a glass of soft, small cider. The thinner
my diet, the easier, more cheerful and lightsome I find
myself; my sleep is also the sounder, though perhaps
somewhat shorter than formerly under my full animal diet;
but then I am more alive than ever I was. As soon as I wake I
get up. I rise commonly at six, and go to bed at ten.”
As for the effect of this regimen, he tells us that
“since that time [his last lapse] I thank God I have
58. gone on in one constant tenor of diet, and enjoy as
good health as, at my time of life (being now sixty), I
or any man can reasonably expect.” When we
remember the complicity of maladies of which he
had been the victim during his adhesion to the
orthodox mode of living, such experience is
sufficiently significant. Some ten years later he
records his experiences as follows:—
“It is now about sixteen years since, for the last time, I
entered upon a milk and vegetable diet. At the beginning of
this period, this light food I took as my appetite directed,
without any measures, and found myself easy under it. After
some time, I found it became necessary to lessen this
quantity, and I have latterly reduced it to one-half, at most, of
what I at first seemed to bear; and if it should please God to
spare me a few years longer, in order to preserve, in that
case, that freedom and clearness which by his presence I
now enjoy, I shall probably find myself obliged to deny myself
one-half of my present daily sustenance, which, precisely, is
three Winchester pints of new milk, and six ounces of biscuit,
made without salt or yeast, baked in a quick oven.”[142]—
[Natural Method of Curing Diseases, &c., page 298; see also
Preface to Essay on Regimen].
The last production of Dr. Cheyne was his
“Natural Method of Curing the Diseases of the Body,
and the Disorders of the Mind Depending on the
Body. In three parts. Part I.—General Reflections on
the Economy of Nature in Animal Life. Part II.—The
Means and Methods for Preserving Life and Faculties;
59. and also Concerning the Nature and Cure of Acute,
Contagious, and Cephalic Disorders. Part III.—
Reflections on the Nature and Cure of Particular
Chronic Distempers. 8vo. Strahan, London, 1742.” It
is dedicated to the celebrated Lord Chesterfield, who
records his grateful recognition of the benefits he
had experienced from his methods. He writes: “I
read with great pleasure your book, which your
bookseller sent me according to your direction. The
physical part is extremely good, and the
metaphysical part may be so too, for what I know,
and I believe it is, for as I look upon all metaphysics
to be guess work of imagination, I know no
imagination likelier to hit upon the right than yours,
and I will take your guess against any other
metaphysician’s whatsoever. That part which is
founded upon knowledge and experience I look upon
as a work of public utility, and for which the present
age and their posterity may be obliged to you, if they
will be pleased to follow it.” Lord Chesterfield, it will
be seen below, was one of those more refined minds
whose better conscience revolted from, even if they
had not the courage or self-control to renounce, the
Slaughter House.
The Natural Method its author considers as a kind
of supplement to his last book, containing “the
practical inferences, and the conclusions drawn from
60. [its principles], in particular cases and diseases,
confirmed by forty years’ experience and
observation.” It is the most practical of all his works,
and is full of valuable observations. Very just and
useful is his rebuke of that sort of John-Bullism which
affects to hold “good living” not only as harmless but
even as a sort of merit—
“How it may be in other countries and religions I will not
say, but among us good Protestants, abstinence, temperance,
and moderation (at least in eating), are so far from being
thought a virtue, and their contrary a vice, that it would seem
that not eating the fattest and most delicious, and to the top,
were the only vice and disease known among us—against
which our parents, relatives, friends, and physicians exclaim
with great vehemence and zeal. And yet, if we consider the
matter attentively we shall find there is no such danger in
abstinence as we imagine, but, on the contrary, the greatest
abstinence and moderation nature and its external laws will
suffer us to go into and practise for any time, will neither
endanger our health, nor weaken our just thinking, be it ever
so unlimited or unrestrained.... And it is a wise providence
that Lent time falls out at that season which, if kept according
to its original intention, in seeds and vegetables well dressed
and not in rich high-dressed fish, would go a great way to
preserve the health of the people in general, as well as
dispose them to seriousness and reflection—so true it is that
‘godliness has the promise of this life, and of that which is to
come,’ and it is very observable that in all civil and established
religious worships hitherto known among polished nations
Lents, days of abstinence, seasons of fasting and bringing
down the brutal part of the rational being, have had a large
share, and been reckoned an indispensable part of their
61. worship and duty, except among a wrong-headed part of our
Reformation, where it has been despised and ridiculed into a
total neglect. And yet it seems not only natural and
convenient for health, but strongly commended both in the
Old and New Testament, and might allow time and proper
disposition for more serious and weighty purposes. And this
‘Lent,’ or times of abstinence, is one reason of the
cheerfulness or serenity of some Roman Catholic or Southern
countries, which would be still more healthy and long-lived
were it not for their excessive use of aromatics and opiates,
which are the worst kind of dry drams, and the cause of their
unnatural and unbridled lechery and shortness of life.”
Denouncing the general practice of the Profession
of encouraging their patients in indulging vitiated
habits and tastes, he reminds them:—
“That such physicians do not consider that they are
accountable to the community, to their patients, to their
conscience, and to their Maker, for every hour and moment
they shorten and cut off their patients’ lives by their immoral
and murderous indulgence: and the patients do not duly
ponder that suicide (which this is in effect) is the most mortal
and irremissible of all sins, and neither have sufficiently
weighed the possibility that the patient, if not quickly cut off
by both these preposterous means, may linger out miserably,
and be twenty or thirty years a-dying, under these heart and
wheel-breaking miseries thus exasperated; whereas, by the
methods I propose, if they obtain not in time a perfect cure,
yet they certainly lessen their pain, lengthen their days, and
continue under the benign influence of ‘the Sun of
Righteousness, who has healing in His wings,’ and, at worst,
soften and lighten the anguish of their dissolution, as far as
the nature of things will admit.”
62. Not the least useful and instructive portions of his
treatise are his references to the proper regimen for
mental diseases and disordered brains, which, he
reasonably infers, are best treated by the adoption of
a light and pure dietary. He despairs, however, of the
general recognition, or at least adoption, of so
rational a method by the “faculty” or the public at
large,
“Who do not consider that nine parts in ten of the whole
mass of mankind are necessarily confined to this diet (of
farinacea, fruits, &c.), or pretty nearly to it, and yet live with
the use of their senses, limbs, and faculties, without diseases
or with but few, and those from accidents or epidemical
causes; and that there have been nations, and now are
numbers of tribes, who voluntarily confine themselves to
vegetables only, ... and that there are whole villages in this
kingdom whose inhabitants scarce eat animal food or drink
fermented liquors a dozen times a year.”
In regard to all nervous and brain diseases, he
insists that the reformed diet would
“Greatly alleviate and render tolerable original distempers
derived from diseased parents, and that it is absolutely
necessary for the deep-thinking part of mankind, who would
preserve their faculties ripe and pregnant to a green old age
and to the last dregs of life; and that it is the true and real
antidote and preservative from wrong-headedness, irregular
and disorderly intellect and functions, from loss of the rational
faculties, memory, and senses, as far as the ends of
63. Providence and the condition of mortality will allow.”—(Nat.
Method, page 90.)
This benevolent and beneficent dietetic reformer,
according to the testimony of an eye-witness,
exemplified by his death the value of his principles—
relinquishing his last breath easily and tranquilly,
while his senses remained entire to the end. During
his last illness he was attended by the famous David
Hartley, noticed below. He was buried at Weston,
near Bath. His character is sufficiently seen in his
writings which, if they contain some metaphysical or
other ideas which our reason cannot always endorse,
in their practical teaching prove him to have been
actuated by a true and earnest desire for the best
interests of his fellow-men. One of the merits of
Cheyne’s writings is his discarding the common
orthodox esoteric style of his profession, who seem
jealously to exclude all but the “initiated” from their
sacred mysteries. One of his biographers has
remarked upon this point that “there is another
peculiarity about most of Dr. Cheyne’s writings which
is worthy of notice. Although there are many
passages that are quite unintelligible to the reader
unless he possesses a considerable knowledge, not
only of medicine but also of mathematics, yet there
is no doubt but that the greater part of his works
were intended for popular perusal, and in this
64. undertaking he is one of the few medical writers who
have been completely successful. His productions,
which were much read and had an extensive
influence in their day, procured him a considerable
degree of reputation, not only with the public, but
also with the members of his own profession. If they
present to the reader no great discoveries (?) they
possess the merit of putting more prominently
forward some useful but neglected truths; and
though now, probably, but little read, they contain
much matter that is well worth studying, and have
obtained for their author a respectable place in the
history of medical literature.”[143]
Our notice of the author of the Essay on
Regimen, &c., would scarcely be complete without
some reference to his friendship with two
distinguished characters—John Wesley and Samuel
Richardson,[144]
the author of Pamela. It was to Dr.
Cheyne that Wesley, as he tells us in his journals,
was indebted for his conversion to those dietetic
principles to which he attributes, in great measure,
the invigoration of his naturally feeble constitution,
and which enabled him to undergo an amount of
fatigue and toil, both mentally and bodily, seldom or
never surpassed. Of Cheyne’s friendship for
Richardson there are several memorials preserved in
his familiar letters to that popular writer; and his free
65. and naïve criticisms of his novels are not a little
amusing. The novelist, it seems, was one of his
patients, and that he was not always a satisfactory
one, under the abstemious regimen, appears
occasionally from the remonstrances of his adviser.
66. XX.
POPE. 1688–1744.
THE most epigrammatic, and one of the most elegant,
of poets. He was also one of the most precocious.
His first production of importance was his Essay on
Criticism, written at the age of twenty-one, although
not published until two years later. But he had
composed, we are assured, several verses of an Epic
at the age of twelve; and his Pastorals was given to
the world by a youth of sixteen. Its division into the
Four Seasons is said to have suggested to Thomson
the title of his great poem. The MS. passed through
the hands of some distinguished persons, who loudly
proclaimed the merits of the boy-poet.
In the same year with his fine mock-heroic Rape
of the Lock (1712) appeared The Messiah, in
imitation of Isaiah and of Virgil (in his well-known
Eclogue IV.), both of whom celebrate, in similar
strains, the advent of a “golden age” to be. The
“Sybilline” prophecy, which Pope supposes the Latin
poet to have read, existed, it need scarcely be
67. added, only in the imagination of himself and of the
authorities on whom he relied. Windsor Forest
(1713) deserves special notice as one of the earliest
of that class of poems which derive their inspiration
directly from Nature. It was the precursor of The
Seasons, although the anti-barbarous feeling is less
pronounced in the former. We find, however, the
germs of that higher feeling which appears more
developed in the Essay on Man; and the following
verses, descriptive of the usual “sporting” scenes, are
significant:—
68. “See! from the brake the whirring Pheasant springs,
And mounts exulting on triumphant wings:
Short is his joy; he feels the fiery wound,
Flutters in blood, and panting beats the ground.
Ah, what avail his glossy, varying dyes,
His purple crest and scarlet-circled eyes—
The vivid green his shining plumes unfold,
His painted wings, and breast that flames with gold?
* * * * * * * *
To plains with well-breathed beagles they repair,
And trace the mazes of the circling Hare.
Beasts, urged by us, their fellow-beasts pursue,
And learn of man each other to undo.
With slaughtering guns the unwearied fowler roves,
When frosts have whitened all the naked groves,
Where Doves, in flocks, the leafless trees o’ershade,
And lonely Woodcocks haunt the watery glade—
He lifts the tube, and level with his eye,
Straight a short thunder breaks the frozen sky.
Oft, as in airy rings they skim the heath,
The clamorous Lapwings feel the leaden death:
Oft, as the mounting Larks their notes prepare,
They fall and leave their little lives in air.”
His Epistle of Eloisa to Abelard (a romantic
version of a very realistic story), Temple of Fame,
Imitations of Chaucer, translation of the Iliad (1713–
1720)—characterised by Gibbon as having “every
merit but that of likeness to its original”—an edition
of Shakspere, The Dunciad (1728), translation of the
Odyssey, are some of the works which attest his
genius and industry. But it is with his Moral Essays—
69. and in particular the Essay on Man (1732–1735), the
most important of his productions—that we are
especially concerned.
As is pretty well known, these Essays owe their
conception, in great part, to his intimate friend St.
John Bolingbroke. Although the author by birth and,
perhaps, still more from a feeling of pride which
might make him reluctant to abandon an
unfashionable sect (such it was at that time),
belonged nominally to the Old Church, the theology
and metaphysics of the work display little of
ecclesiastical orthodoxy. The pervading principles of
the Essay on Man are natural theology or, as
Warburton styles it, “Naturalism” (i.e., the putting
aside human assertion for the study of the attributes
of Deity through its visible manifestations) and
Optimism.[145]
The merits of the Essay, it must be added, consist
not so much in the philosophy of the poem as a
whole as in the many fine and true thoughts
scattered throughout it, which the author’s
epigrammatic terseness indelibly fixes in the mind. Of
the whole poem the most valuable part, undoubtedly,
is its ridicule of the common arrogant (pretended)
belief that all other species on the earth have been
brought into being for the benefit of the human race
—an egregious fallacy, by the way, which, ably
70. exposed as it has been over and over again, still
frequently reappears in our popular theology and
morals. To the writers and talkers of this too
numerous class may be commended the rebukes of
Pope:—
“Nothing is foreign—parts relate to whole:
One all-extending, all-preserving soul
Connects each being, greatest with the least—
Made beast in aid of man, and man of beast:
All served, all serving—nothing stands alone.
* * * * * * *
Has God, thou fool, worked solely for thy good,
Thy joy, thy pastime, thy attire, thy food?
* * * * * * *
Is it for thee the Lark ascends and sings?
Joy tunes his voice, joy elevates his wings.
Is it for thee the Linnet pours his throat?
Loves of his own and raptures swell the note.
The bounding Steed you pompously bestride
Shares with his lord the pleasure and the pride.
* * * * * * *
Know Nature’s children all divide her care,
The fur that warms a monarch warmed a Bear.
While Man exclaims, ‘See all things for my use!’
‘See Man for mine!’ replies a pampered Goose.
And just as short of reason he must fall,
Who thinks all made for one, not one for all.”
He then paints the picture of the “Times of
Innocence” of the Past, or rather (as we must take
it) of the Future:—
71. “No murder clothed him, and no murder fed.
In the same temple—the resounding wood—
All vocal beings hymned their equal God.
The shrine, with gore unstained, with gold undrest,
Unbribed, unbloody, stood the blameless priest.
Heaven’s attribute was universal care,
And man’s prerogative to rule but spare.
Ah, how unlike the man of times to come—
Of half that live the butcher and the tomb!
Who, foe to Nature, hears the general groan,
Murders their species, and betrays his own.
But just disease to luxury succeeds,
And every death its own avenger breeds:
The fury-passions from that blood began,
And turned on man a fiercer savage, man.”
Again, depicting the growth of despotism and
superstition, and speculating as to—
“Who first taught souls enslaved and realms undone
The enormous faith of Many made for One?”
he traces the gradual horrors of sacrifice
beginning with other, and culminating in that of the
human, species:—
72. “She [Superstition] from the rending earth and bursting skies
Saw gods descend, and fiends infernal rise:
Here fixed the dreadful, there the blest, abodes—
Fear made her devils and weak Hope her gods—
Gods partial, changeful, passionate, unjust,
Whose attributes were rage, revenge, or lust—
Such as the souls of cowards might conceive,
And, formed like tyrants, tyrants would believe.
* * * * * * * *
Altars grew marble then, and reeked with gore;
Then first the Flamen tasted living food,
Next his grim idol smeared with human blood.
With Heaven’s own thunders shook the earth below,
And played the God an engine on his foe.”
Whenever occasion arises, Pope fails not to
stigmatise the barbarity of slaughtering for food; and
the sæva indignatio urges him to upbraid his fellows
with the slaughter of—
“The lamb thy riot dooms to bleed,
* * * * * * *
Who licks the hand just raised to shed his blood.”
And, again, he expresses his detestation of the
selfishness of our species who—
“Destroy all creatures for their sport or gust.”
73. That all this was no mere affectation of feeling
appears from his correspondence and contributions
to the periodicals of the time:—
“I cannot think it extravagant,” he writes, “to imagine that
mankind are no less, in proportion, accountable for the ill use
of their dominion over the lower ranks of beings, than for the
exercise of tyranny over their own species. The more entirely
the inferior creation is submitted to our power, the more
answerable we must be for our mismanagement of them; and
the rather, as the very condition of Nature renders them
incapable of receiving any recompense in another life for ill-
treatment in this.”[146]
Consistently with the expression of this true
philosophy, he declares elsewhere that—
“Nothing can be more shocking and horrid than one of our
kitchens sprinkled with blood, and abounding with the cries of
expiring victims, or with the limbs of dead animals scattered
or hung up here and there. It gives one the image of a giant’s
den in romance, bestrewed with scattered heads and
mangled limbs.”[147]
The personal character of Pope, we may add, has
of late been subjected to minute and searching
criticism. Some meannesses, springing from an
extreme anxiety for fame with after ages, have
undoubtedly tarnished his reputation for candour. His
excessive animosity towards his public or private
enemies may be palliated in part, if not excused, by
74. his well-known feebleness of health and consequent
mental irritability. For the rest, he was capable of the
most sincere and disinterested attachments; and not
his least merit, in literature, is that in an age of
servile authorship he cultivated literature not for
place or pay, but for its own sake.
Amongst Pope’s intimate friends were Dr.
Arbuthnot, Dean Swift, and Gay. The first of these,
best known as the joint author with Pope and Swift
of Martinus Scriblerus, a satire on the useless
pedantry prevalent in education and letters, and
especially as the author of the History of John Bull
(the original of that immortal personification of beef,
beer, and prejudice), published his Essay Concerning
Aliments, in which the vegetable diet is commended
as a preventive or cure of certain diseases, about the
year 1730. Not the least meritorious of his works was
an epitaph on the notorious Colonel Chartres—one of
the few epitaphs which are attentive less to custom
than to truth, and, we may add, in marked contrast
with that typical one on his unhistorical
contemporary Captain Blifil.
In the Travels of Lemuel Gulliver the reader will
find the sæva indignatio of Swift—or, at all events, of
75. the Houyhnhnms—amongst other things, launched
against the indiscriminating diet of his countrymen:—
“I told him” [the Master-Horse], says Gulliver, “we fed on a
thousand things which operated contrary to each other—that
we eat when we are not hungry, and drink without the
provocation of thirst ... that it would be endless to give him a
catalogue of all diseases incident to human bodies, for they
could not be fewer than five or six hundred, spread over
every limb and joint—in short, every part, external and
intestine, having diseases appropriated to itself—to remedy
which there was a sort of people bred up among us in the
profession or pretence of curing the sick.”
Among the infinite variety of remedies and
prescriptions, in the human Materia Medica, the
astounded Houyhnhnm learns, are reckoned
“serpents, toads, frogs, spiders, dead men’s flesh
and bones, birds, beasts, fishes”—no mere travellers’
tales (it is perhaps necessary to explain), but sober
fact, as any one may discover for himself by an
examination of some of the received and popular
medical treatises of the seventeenth century, in
which the most absurd “prescriptions,” involving the
most frightful cruelty, are recorded with all
seriousness:—
“My master, continuing his discourse, said there was
nothing that rendered the Yahoos more odious than their
undistinguishing appetite to devour everything that came in
their way, whether herbs, roots, berries, the corrupted flesh
76. of animals, or all mingled together; and that it was peculiar in
their temper that they were fonder of what they could get by
rapine or stealth at a greater distance than much better food
provided for them at home. If their prey held out, they would
eat till they were ready to burst.”
Although unaccustomed to the better living, and
finding it “insipid at first,” the human slave of the
Houyhnhnm (a word which, by the way, in that
language, means “the perfection of nature”) records
as the result of his experience, in the first place, how
little will sustain human life; and, in the second
place, the fact of the superior healthfulness of the
vegetable food.[148]
About this period or a little earlier, Philippe
Hecquet, a French physician, published his Traité des
Dispenses du Carême (“Treatise on Dispensations in
Lent”), 1709, in which he gave in his adhesion to the
principles of Vegetarianism—at all events, so far as
health is concerned. He is mentioned by Voltaire, and
is supposed to be the original of the doctor Sangrado
of Le Sage.[149]
If this conjecture have any truth, the
author of Gil Blas is open to the grave charge of
misrepresentation, of sacrificing truth to effect, or
(what is still worse and still more common) of
pandering to popular prejudices.[150]
77. XXI.
THOMSON. 1700–1748.
IN the long and terrible series of the Ages the
distinguishing glory of the eighteenth century is its
Humanitarianism—not visible, indeed, in legislation
or in the teaching of the ordinarily-accredited guides
of the public faith and morals, but proclaimed,
nevertheless, by the great prophets of that era. As
far as ordinary life was concerned, the last age is
only too obnoxious to the charge of selfishness and
heartlessness. Callousness to suffering, as regards
the non-human species in particular, is sufficiently
apparent in the common amusements and
“pastimes” of the various grades of the community.
Yet, if we compare the tone of even the common-
place class of writers with that of the authors of
quasi-scientific treatises of the preceding century—in
which the most cold-blooded atrocities on the
helpless victims of human ignorance and barbarity
are prescribed for the composition of their medical
nostrums, &c., with the most unconscious audacity
78. and ignoring of every sort of feeling—considerable
advance is apparent in the slow onward march of the
human race towards the goal of a true morality and
religion.
To the author of The Seasons belongs the
everlasting honour of being the first amongst
modern poets earnestly to denounce the manifold
wrongs inflicted upon the subject species, and, in
particular, the savagery inseparable from the
Slaughter-House—for Pope did not publish his Essay
on Man until four years after the appearance of
Spring.
James Thomson, of Scottish parentage, came to
London to seek his fortune in literature, at the age of
25. For some time he experienced the poverty and
troubles which so generally have been the lot of
young aspirants to literary, especially poetic, fame.
Winter—which inaugurated a new school of poetry—
appeared in March, 1726. That the publisher
considered himself liberal in offering three guineas
for the poem speaks little for the taste of the time;
but that a better taste was coming into existence is
also plain from the fact of its favourable reception,
notwithstanding the obscurity of the author. Three
editions appeared in the same year. Summer, his
next venture, was published in 1727, and the (Four)
79. Seasons in 1730, by subscription—387 subscribers
enrolling their names for copies at a guinea each.
Natural enthusiasm, sympathy, and love for all
that is really beautiful on Earth (a sort of feeling not
to be appreciated by vulgar minds) forms his chief
characteristic. But, above all, his sympathy with
suffering in all its forms (see, particularly, his
reflections after the description of the snowstorm in
Winter), not limited by the narrow bounds of
nationality or of species but extended to all innocent
life—his indignation against oppression and injustice,
are what most honourably distinguish him from
almost all of his predecessors and, indeed, from most
of his successors. The Seasons is the forerunner of
The Task and the humanitarian school of poetry. The
Castle of Indolence in the stanza of Spenser, has
claims of a kind different from those of The Seasons;
and the admirers of The Faerie Queen cannot fail to
appreciate the merits of the modern romance.
Besides these chefs-d’œuvre Thomson wrote two
tragedies, Sophonisba and Liberty, the former of
which, at the time, had considerable success upon
the stage. In the number of his friends he reckoned
Pope and Samuel Johnson, both of whom are said to
have had some share in the frequent revisions which
he made of his principal production.
80. It is with his Spring that we are chiefly
concerned, since it is in that division of his great
poem that he eloquently contrasts the two very
opposite diets. Singing the glories of the annual
birth-time and general resurrection of Nature, he first
celebrates
“The living Herbs, profusely wild,
O’er all the deep-green Earth, beyond the power
Of botanist to number up their tribes,
(Whether he steals along the lonely dale
In silent search, or through the forest, rank
With what the dull incurious weeds account,
Bursts his blind way, or climbs the mountain-rock,
Fired by the nodding verdure of its brow).
With such a liberal hand has Nature flung
Their seeds abroad, blown them about in winds,
Innumerous mixed them with the nursing mould,
The moistening current and prolific rain.
But who their virtues can declare? Who pierce,
With vision pure, into those secret stores
Of health and life and joy—the food of man,
While yet he lived in innocence and told
A length of golden years, unfleshed in blood?
A stranger to the savage arts of life—
Death, rapine, carnage, surfeit, and disease—
The Lord, and not the Tyrant, of the world.”
And then goes on to picture the feast of blood:—
81. “And yet the wholesome herb neglected dies,
Though with the pure exhilarating soul
Of nutriment and health, and vital powers
Beyond the search of Art, ’tis copious blessed.
For, with hot ravin fired, ensanguined Man
Is now become the Lion of the plain
And worse. The Wolf, who from the nightly fold
Fierce drags the bleating Prey, ne’er drank her milk,
Nor wore her warming fleece; nor has the Steer,
At whose strong chest the deadly Tiger hangs,
E’er ploughed for him. They, too, are tempered high,
With hunger stung and wild necessity,
Nor lodges pity in their shaggy breast.
But Man, whom Nature formed of milder clay,
With every kind emotion in his heart,
And taught alone to weep; while from her lap
She pours ten thousand delicacies—herbs
And fruits, as numerous as the drops of rain
Or beams that gave them birth—shall he, fair form,
Who wears sweet smiles and looks erect on heaven,
E’er stoop to mingle with the prowling herd
And dip his tongue in gore? The beast of prey,
Blood-stained, deserves to bleed. But you, ye Flocks,
What have you done? Ye peaceful people, what
To merit death? You who have given us milk
In luscious streams, and lent us your own coat
Against the winter’s cold? And the plain Ox,
That harmless, honest, guileless animal,
In what has he offended? He, whose toil,
Patient and ever ready, clothes the land
With all the pomp of harvest—shall he bleed,
And struggling groan beneath the cruel hands
E’en of the clowns he feeds, and that, perhaps,
To swell the riot of the autumnal feast
W b hi l b ?”[151]
82. Won by his labour?”[151]
And again in denouncing the amateur
slaughtering (euphemised by the mocking term of
Sport) unblushingly perpetrated in the broad light of
day:—
“When beasts of prey retire, that all night long,
Urged by necessity, had ranged the dark,
As if their conscious ravage shunned the light,
Ashamed. Not so [he reproaches] the steady tyrant Man,
Who with the thoughtless insolence of Power,
Inflamed beyond the most infuriate wrath
Of the worst monster that e’er roamed the waste,
For Sport alone pursues the cruel chase,
Amid the beamings of the gentle days.
Upbraid, ye ravening tribes, our wanton rage,
For hunger kindles you, and lawless want;
But lavish fed, in Nature’s bounty rolled—
To joy at anguish, and delight in blood—
Is what your horrid bosoms never knew.”[152]
We conclude these extracts from The Seasons
with the poet’s indignant reflection upon the selfish
greed of Commerce, which barbarously sacrifices by
thousands (as it does also the innocent mammalia of
the seas) the noblest and most sagacious of the
terrestrial races for the sake of a superfluous luxury:
—
83. “Peaceful, beneath primeval trees, that cast
Their ample shade o’er Niger’s yellow stream,
And where the Ganges rolls his sacred waves;
Or mid the central depth of blackening woods,
High raised in solemn theatre around,
Leans the huge Elephant, wisest of brutes!
O truly wise! with gentle might endowed:
Though powerful, not destructive. Here he sees
Revolving ages sweep the changeful Earth,
And empires rise and fall: regardless he
Of what the never-resting race of men
Project. Thrice happy! could he ’scape their guile
Who mine, from cruel avarice, his steps:
Or with his towering grandeur swell their state—
The pride of kings!—or else his strength pervert,
And bid him rage amid the mortal fray,
Astonished at the madness of mankind.”[153]
84. Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com