Professional Documents
Culture Documents
(Download PDF) Go Cookbook Expert Solutions For Commonly Needed Go Tasks First Early Release Sau Sheong Chang Ebook Online Full Chapter
(Download PDF) Go Cookbook Expert Solutions For Commonly Needed Go Tasks First Early Release Sau Sheong Chang Ebook Online Full Chapter
(Download PDF) Go Cookbook Expert Solutions For Commonly Needed Go Tasks First Early Release Sau Sheong Chang Ebook Online Full Chapter
https://ebookmeta.com/product/go-cookbook-expert-solutions-for-
commonly-needed-go-tasks-1st-edition-sau-sheong-chang/
https://ebookmeta.com/product/learning-go-2nd-edition-early-
release-jon-bodner/
https://ebookmeta.com/product/learning-go-2nd-edition-4th-early-
release-jon-bodner/
https://ebookmeta.com/product/efficient-go-data-driven-
performance-optimization-fourth-early-release-bartlomiej-plotka/
Go Programming Blueprints Build real world production
ready solutions in Go using cutting edge technology and
techniques Ryer
https://ebookmeta.com/product/go-programming-blueprints-build-
real-world-production-ready-solutions-in-go-using-cutting-edge-
technology-and-techniques-ryer/
https://ebookmeta.com/product/gitops-cookbook-third-early-
release-natale-vinto/
https://ebookmeta.com/product/azure-cookbook-4th-early-release-
fourth-early-release-2023-06-22-edition-reza-salehi/
https://ebookmeta.com/product/let-s-go-let-s-go-let-s-go-1st-
edition-cleo-qian-2/
https://ebookmeta.com/product/let-s-go-let-s-go-let-s-go-1st-
edition-cleo-qian/
Go Cookbook
Expert Solutions for Commonly Needed Go Tasks
With Early Release ebooks, you get books in their earliest form—the author’s
raw and unedited content as they write—so you can take advantage of these
technologies long before the official release of these titles.
1.0 Introduction
Input and output (or more popularly known as I/O) is how a
computer communicates with the external world. I/O is a key part of
developing software and therefore most programming languages,
including Go, has standard libraries that can read from input and
write to output. Typical input into a computer refers to the
keystrokes from a keyboard or clicks or movement from a mouse,
but can also refer to other external sources like a camera or a
microphone, or gaming joystick and so on. Output in many cases
refer to whatever is shown on the screen (or on the terminal) or
printed out on a printer. I/O can also refer to network connections
and often also to files.
In this chapter, we’ll be exploring some common Go recipes for
managing I/O. We’ll warm up with with some basic I/O recipes, then
talk about files in general. In the next few chapters we’ll move on to
CSV, followed by JSON and also binary files.
The io package is the base package for input and output in Go. It
contains the main interfaces for I/O and a few convenient functions.
The main and the most commonly used interfaces are Reader and
Writer but there are a number of variants of these like the
ReadWriter, TeeReader, WriterTo and many more.
Generally these interfaces are nothing more than a descriptor for
functions, for example a struct that is a Reader is one that has a
Read function. A struct that is a WriterTo is one with a WriteTo
function. Some interfaces combine more two or more interfaces for
example, the ReadWriter combines the Reader and Writer
interfaces and has both the Read and Write functions.
This chapter explains a bit more about how these interfaces are
used.
Problem
You want to read from an input.
Solution
Use the io.Reader interface to read from an input.
Discussion
Go uses the io.Reader interface to represent the ability to read
from an input stream of data. Many packages in the Go standard
library as well as 3rd party packages use the Reader interface to
allow data to be read from it.
Any struct that implement the Read function is a Reader. Let’s say
you have a reader (a struct that implements the Reader interface).
To read data from the reader, you make a slice of bytes and you
pass that slice to the Read method.
It might look counterintuitive and seems like you would want to read
data from bytes into the reader, but you’re actually reading the
data from the reader into bytes. Just think of it as the data flowing
from left to right, from the reader into bytes.
Read will only fill up the bytes to its capacity. If you want to read
everything from the reader, you can use the io.ReadAll function.
This looks more intuitive because the ReadAll reads from the
reader passed into the parameter and returns the data into bytes.
In this case, the data flows from the reader on the right, into the
bytes on the lft.
You will also often find functions that expect a reader as an input
parameter. Let’s say you have a string and you want to pass the
string to the function, what can you do? You can create a reader
from the string using the strings.NewReader function then pass
it into the function.
You can now pass reader into functions that expect a reader.
1.2 Writing to an Output
Problem
You want to write to an output.
Solution
Use the io.Writer interface to write to an output.
Discussion
The interface io.Writer works the same way as io.Reader.
When you call Write on an io.Writer you are writing the bytes
to the underlying data stream.
You might notice that this method calling pattern is the reverse of
io.Reader in recipe 8.1. In Reader you call the Read method to
read from the struct into the bytes variable, whereas here you call
the Write method to write from the bytes variable into the struct.
In this case, the data flows from right to left, from bytes into the
writer.
A common pattern in Go is for a function to take in a writer as a
parameter. The function then calls the Write function on the writer,
and later you can extract the data from writer. Let’s take a look at an
example of this.
var buf bytes.Buffer
fmt.Fprintf(&buf, "Hello %s", "World")
s := buf.String() // s == "Hello World"
Problem
You want to copy from a reader to a writer.
Solution
Use the io.Copy function to copy from a reader to a writer.
Discussion
Sometimes we read from a reader because we want to write it to a
writer. The process can take a few steps to read everything from a
reader into buffer then write it out to the writer again. Instead of
doing this, we can use the io.Copy function instead. The io.Copy
function takes from a reader and writes to a writer all in one
function.
Let’s see how io.Copy can be used. We want to download a file, so
we use http.Get to get a reader, which we read and then we use
os.WriteFile to write to a file.
func readWrite() {
r, err := http.Get(url)
if err != nil {
log.Println("Cannot get from URL", err)
}
defer r.Body.Close()
data, _ := os.ReadAll(r.Body)
os.WriteFile("rw.data", data, 0755)
}
package main
import "testing"
func BenchmarkReadWrite(b *testing.B) {
readWrite()
}
We use the -bench=. flag telling Go to run all the benchmark tests
and -benchmem flag to show memory benchmarks. This is what you
should see.
goos: darwin
goarch: amd64
pkg: github.com/sausheong/go-cookbook/io/copy
cpu: Intel(R) Core(TM) i7-7920HQ CPU @ 3.10GHz
BenchmarkReadWrite-8 1 1998957055 ns/op
5892440 B/op
219 allocs/op
PASS
ok github.com/sausheong/go-cookbook/io/copy
2.327s
First, we need to create a file for the data, here using os.Create.
Next we create a buffered writer using bufio.NewWriter,
wrapping around the file. This will be used in the Copy function,
copying the contents of the response Body into the buffered writer.
Finally we flush the writer’s buffers and make the underlying writer
write to the file.
If you run this, copy function it works the same way, but how does
the performance compare? Let’s go back to our benchmark and add
another benchmark function for this copy function.
package main
import "testing"
We run the benchmark again and this is what you should see.
goos: darwin
goarch: amd64
pkg: github.com/sausheong/go-cookbook/io/copy
cpu: Intel(R) Core(TM) i7-7920HQ CPU @ 3.10GHz
BenchmarkReadWrite-8 1 2543665782 ns/op
5895360 B/op
227 allocs/op
BenchmarkCopy-8 1 1426656774 ns/op
42592 B/op
61 allocs/op
PASS
ok github.com/sausheong/go-cookbook/io/copy
4.103s
This time the readWrite function took 2.54 seconds, used 5.89 MB
of memory and did 227 memory allocations. The copy function
however only too 1.43 seconds, used 42.6 kB of memory and did 61
memory allocations.
The copy function is around 80% faster, but uses only a fraction
(less than 1%) of the memory. With really large files, if you’re using
the os.ReadAll and os.WriteFile you might run out of
memory quickly.
Problem
You want to read a text file into memory.
Solution
You can usethe os.Open function to open the file, followed by Read
on the file. Alternatively you can also use the simpler os.ReadFile
function to do it in a single function call.
Discussion
Reading and writing to the filesystem are one of the basic things a
programming language needs to do. Of course you can always store
in memory but sooner or later if you need to persist the data beyond
a shutdown you need to store it somewhere. There are a number of
ways that data can be persistent but the most commonly accessible
is probably to the local filesystem.
hello world!
To read the file, just give the name of the file as a parameter to
os.ReadFile and you’re done!
To do this, we need to know how large the byte array should be, and
that should be the size of the file. We use the Stat method on the
file to get a FileInfo struct, which we can call the Size method
to get the size of the file.
Once we have the byte array, we can pass it as a parameter to the
Read method on the file struct.
This will store the read data into the byte array and return the
number of bytes read. If all goes well you should see something like
this from the output.
There are a few more steps, but you have the flexibility of reading
parts of the whole document and you can also do other stuff in
between opening the file and reading it.
1.5 Writing to a Text File
Problem
You want to write data a text file.
Solution
You can use the os.Open function to open the file, followed by
Write on the file. Alternatively you can use the os.WriteFile
function to do it in a single function call.
Discussion
Just as in reading a file, there are a couple of ways of writing to a
file.
The first parameter is the name of the file, the data is in a byte array
and the final parameter is the Unix file permissions you want to give
to the file. If the file doesn’t exist, this will create a new file. If it
exists, it will remove all the data in the file and write the new data
into it, but without changing the permissions.
Creating a file and writing to it
Writing to a file by creating the file and then writing to it is a bit
more involved but it’s also more flexible. First, you need to create or
open a file using the os.Create function.
This will create a new file with the given name and mode 0666 if
the file doesn’t exist. If the file exists, this will remove all the data in
it. As before you would want to set up the file to be closed at the
end of the function, using the defer keyword.
Once you have the file you can write to it directly using the Write
method and passing it the byte array with the data.
This will return the number of bytes that was written to the file. As
before while it takes a few more steps, breaking up the steps
between creating a file and writing to it gives you more flexibility to
write in smaller chunks instead of everything at once.
1.6 Using a Temporary File
Problem
You want to create a temporary file for use and depose of it
afterwards.
Solution
Use the os.CreateTemp function to create a temporary file, and
then remove it once you don’t need it anymore.
Discussion
A temporary file is a file that’s created to store data temporarily
while the program is doing something. It’s meant to be deleted or
copied to permanent storage once the task is done. In Go, we can
use os.CreateTemp function to create a temporary file. Then after
that we can remove it.
Different operating systems store their temporary files in different
places. Regardless where it is, Go will let you know where it is using
the os.TempDir function.
fmt.Println(os.TempDir())
/var/folders/nj/2xd4ssp94zz41gnvsyvth38m0000gn/T/
This is the directory that your computer tells Go (and some other
programs) to use as a temporary directory. We can use this directly
or we can create our own directory here using the os.MkdirTemp
function.
With that, we have a file and everything else works the same way as
any other file.
defer os.Remove(tmpfile.Name())
Chapter 2. CSV Recipes
2.0 Introduction
The CSV format is a file format in which tabular data (numbers and
text) can be easily written and read in a text editor. CSV is widely
supported, and most spreadsheet programs, such as Microsoft Excel
and Apple Numbers, support CSV. Consequently, many programming
languages, including Go, come with libraries that produce and
consume the data in CSV files.
It might come as a surprise to you that CSV has been around for
almost 50 years. The IBM Fortran compiler supported it in OS/360
back in 1972. If you’re not quite sure that that is, OS/360 is the
batch processing operating system developed by IBM for their
System/360 mainframe computer. So yes, one of the first uses for
CSV was for Fortran in an IBM mainframe computer.
CSV (comma separated values) is not very well standardized and not
all CSV formats are separated by commas either. Sometimes it can
be a tab or a semicolon or other delimiters. However, there is a RFC
specification for CSV — the RFC 4180 though not everyone follows
that standard.
The Go standard library has an encoding/csv package that
supports RFC 4180 and helps us to read and write CSV.
Problem
You want to read a CSV file into memory for use.
Solution
Use the encoding/csv package and csv.ReadAll to read all
data in the CSV file into a 2 dimensional array of strings.
Discussion
Let’s say you have a file like this:
id,first_name,last_name,email
1,Sausheong,Chang,sausheong@email.com
2,John,Doe,john@email.com
The first row is the header, the next 2 rows are data for the user.
Here’s the code to open the file and read it into the 2 dimensional
array of strings.
Solution
First read the CSV into a 2-dimensional array of strings then store it
into structs.
Discussion
For some other formats like JSON or XML, it’s common to unmarshal
the data read from file (or anywhere) into structs. You can also do
this in CSV though you need to do a bit more work.
Let’s say you want to put the data into a User struct.
Problem
If your CSV file has a line of headers that are column labels, you will
get that as well in your returned 2 dimensional array of strings or
array of structs. You want to remove it.
Solution
Read the first line using Read and then continue reading the rest.
Discussion
When you use Read on the reader, you will read the first line and
then move the cursor to the next line. If you use ReadAll
afterwards, you can read the rest of the file into the rows that you
want.
Problem
CSV doesn’t necessarily need to use commas as delimiters. You want
to read a CSV file which has delimiter that is not a comma.
Solution
Set the Comma variable in the csv.Reader struct to the delimiter
used in the file and read as before.
Discussion
Let’s say the file we want to read has semi-colons as delimiters.
id;first_name;last_name;email
1;Sausheong;Chang;sausheong@email.com
2;John;Doe;john@email.com
Problem
You want to ignore certain rows when reading the CSV file.
Solution
Use comments in the file to indicate the rows to be ignored. Then
enable coding in the csv.Reader and read the file as before.
Discussion
Let’s say you want to ignore certain rows; what you’d like to do is
simply comment those rows out. Well, in CSV you can’t because
comments are not in the standard. However with the Go
encoding/csv package you can specify a comment rune, which if
you place at the beginning of the row, ignores the entire row.
So say you have this CSV file.
id,first_name,last_name,email
1,Sausheong,Chang,sausheong@email.com
# 2,John,Doe,john@email.com
Problem
You want to write data from memory into a CSV file.
Solution
Use the encoding/csv package and csv.Writer to write to file.
Discussion
We had fun reading CSV files, now we have to write one. Writing is
quite simliar to reading. First you need to create a file (an
io.Writer).
data := [][]string{
{"id", "first_name", "last_name", "email"},
{"1", "Sausheong", "Chang", "sausheong@email.com"},
{"2", "John", "Doe", "john@email.com"},
}
writer := csv.NewWriter(file)
err = writer.WriteAll(data)
if err != nil {
log.Println("Cannot write to CSV file:", err)
}
Problem
Instead of writing everything in our 2 dimensional string, we want to
write to the file one row at a time.
Solution
Use the Write method on csv.Writer to write a single row/
Discussion
Writing to file one row at a time is pretty much the same, except you
will want to iterate the 2 dimensional array of strings to get each
row and then call Write, passing that row. You will also need to call
Flush whenever you want to write the buffered data to the Writer
(the file). In the example above I called Flush after I have written
all the data to the writer, but that’s because I don’t have a lot of
data. If you have a lot of rows, you would probably want to flush the
data to the file once in a while. To check if there’s any problems with
writing or flushing, you can call Error.
writer := csv.NewWriter(file)
for _, row := range data {
err = writer.Write(row)
if err != nil {
log.Println("Cannot write to CSV file:", err)
}
}
writer.Flush()
Another random document with
no related content on Scribd:
and agility, and thought to crown her efforts by a notable feat, which
was no less than standing on her head on the top of the ladder, and
brandishing the two stilts, from which she had disengaged herself,
round about her, like the arms of a windmill. It required no great
skill to see that the old lady was very much offended with this last
performance, for when the little dish was carried to her, and the
ladder-dancer directed a beseeching look accompanied by an attitude
which seemed to imply that there were other feats yet in reserve, if
encouragement was held out, the patroness of the stair-head could
restrain herself no longer, but poured out a torrent partaking both of
objurgation and admonition.
“Ne’er-do-weel hussie,” and “vagrant gipsy,” were some of the
sharp missiles shot at the unsuspecting figurante, who, as little aware
of the meaning of all this “sharp-toothed violence,” as the bird is of
the mischief aimed at him by the fowler, sadly misapprehended its
import, and thinking it conveyed encouragement and approbation,
ducked her head in acknowledgment, while the thunder of the old
lady’s reprobation rolled about her in the most ceaseless rapidity of
vituperation.
“Ye’re a pretty ane indeed, to play sic antics afore ony body’s
house! Hae ye naebody to learn ye better manners that to rin up and
down a ladder like a squirrel, twisting and turning yoursel till my
banes are sair to look at you? Muckle fitter gin ye would read your
Bible, if as much grace be left to ye; or maybe a religious tract, to
begin wi’, for I doubt ye wad need preparation afore ye could drink at
the spring-head wi’ ony special profit.”
The last part was conveyed with a kind of smile of self-
approbation; for of all tasks, to reclaim a sinner is the most pleasing
and soothing to religious vanity;—so comfortable it is to be allowed
to scold on any terms, but doubly delightful, because it always
implies superiority. But the ladder-dancer and her attendant were
aware of no part of what was passing in the mind of the female
lecturer, and fully as ignorant of the eloquent address I have just
repeated; she only saw, in the gracious looks in which her feats were
condemned, an approval of her labours, for it passed her philosophy
to comprehend the ungodly qualities of standing on the head, or
whirling like a top. Again the ladder-dancer cringed and bowed to
her of the stair-head; and her male supporter, who acted as a kind of
pedestal to her elevation, bowed and grinned a little more grimly,
while the boy held out his plate to receive the results of all this
assiduity. But they could not command a single word of broad
English among them. Theirs only was the eloquence of nods and
grimaces; a monkey could have done as much, and in the present
humour of the old lady, would have been as much approved. The
ladder-dancer grew impatient, and seemed determined on an effort
to close her labours.
“Ah, Madame!” she exclaimed; “Madame” was repeated by the
man, and “Madame” was re-echoed by the boy.
“Nane o’ your nonsense wi’ me,” was the response from the stair-
head; “your madam’ing, and I dinna ken what mair havers. Ye
needna fash your head to stand there a’ day girning at me, and
making sic outlandish sport. I’m mair fule than you, that bides to
look at you; a fine tale they’d hae to tell that could say they saw me
here, idling my precious time on the like o’ you.”
She now whispered to one of the girls, who retired, and soon after
returned, giving her a small parcel, which she examined, and seemed
to say all was right. She beckoned the ladder-dancer, who slid down
with cat-like agility, and was instantly with her, standing a step
lower, in deference to the doughty dame.
“Here,” said she, with a gruff air, which was rather affected than
real, “tak these precious gifts,” handing her a bunch of religious
tracts. “See if ye canna find out your spiritual wants, and learn to
seek for the ‘Pearl of Price.’ My certie, but ye’re a weel-faured
hussie,” examining her more narrowly, “but your gaits are no that
commendable; but for a’ that, a mair broken ship has reached the
land.”
I could observe that she slipped a half-crown into the hand of the
Piedmontoise; and as she turned away to avoid thanks, an elderly
gentleman (perhaps her husband), who stood by, said in a low voice,
—
“That’s like yoursel, Darsie; your bark was aye waur than your bite,
ony day!”—Blackwood’s Magazine, 1826.
THE ELDER’S DEATH-BED.
By Professor Wilson.
It was on a fierce and howling day that I was crossing the dreary
moor of Auchindown, on my way to the manse of that parish—a
solitary pedestrian. The snow, which had been incessantly falling for
a week past, was drifted into beautiful but dangerous wreaths, far
and wide, over the melancholy expanse; and the scene kept visibly
shifting before me, as the strong wind that blew from every point of
the compass struck the dazzling masses, and heaved them up and
down in endless transformation. There was something inspiriting in
the labour with which, in the buoyant strength of youth, I forced my
way through the storm; and I could not but enjoy those gleamings of
sunlight that ever and anon burst through some unexpected opening
in the sky, and gave a character of cheerfulness, and even warmth, to
the sides or summits of the stricken hills. Sometimes the wind
stopped of a sudden, and then the air was as silent as the snow—not
a murmur to be heard from spring or stream, now all frozen up over
those high moorlands. As the momentary cessations of the sharp
drift allowed my eyes to look onwards and around, I saw here and
there, up the little opening valleys, cottages just visible beneath the
black stems of their snow-covered clumps of trees, or beside some
small spot of green pasture kept open for the sheep. These
intimations of life and happiness came delightfully to me in the
midst of the desolation; and the barking of a dog, attending some
shepherd in his quest on the hill, put fresh vigour into my limbs,
telling me that, lonely as I seemed to be, I was surrounded by
cheerful, though unseen company, and that I was not the only
wanderer over the snows.
As I walked along, my mind was insensibly filled with a crowd of
pleasant images of rural winter life, that helped me gladly onwards
over many miles of moor. I thought of the severe but cheerful labours
of the barn—the mending of farm-gear by the fireside—the wheel
turned by the foot of old age less for gain than as a thrifty pastime—
the skilful mother making “auld claes look amaist as weel’s the
new”—the ballad unconsciously listened to by the family all busy at
their own tasks round the singing maiden—the old traditionary tale,
told by some wayfarer hospitably housed till the storm should blow
by—the unexpected visit of neighbours on need or friendship—or the
footstep of lover undeterred by snow-drifts that have buried up his
flocks;—but above all, I thought of those hours of religious worship
that have not yet escaped from the domestic life of the peasantry of
Scotland—of the sound of psalms that the depth of the snow cannot
deaden to the ear of Him to whom they are chanted—and of that
sublime Sabbath-keeping which, on days too tempestuous for the
kirk, changes the cottage of the shepherd into the temple of God.
With such glad and peaceful images in my heart, I travelled along
that dreary moor, with the cutting wind in my face, and my feet
sinking in the snow, or sliding on the hard blue ice beneath it—as
cheerfully as I ever walked in the dewy warmth of a summer
morning, through fields of fragrance and of flowers. And now I could
discern, within half an hour’s walk, before me, the spire of the
church, close to which stood the manse of my aged friend and
benefactor. My heart burned within me as a sudden gleam of stormy
sunlight tipped it with fire; and I felt, at that moment, an
inexpressible sense of the sublimity of the character of that
grayheaded shepherd who had, for fifty years, abode in the
wilderness, keeping together his own happy little flock.
As I was ascending a knoll, I saw before me on horseback an old
man, with his long white hairs beaten against his face, who,
nevertheless, advanced with a calm countenance against the
hurricane. It was no other than my father, of whom I had been
thinking—for my father had I called him for many years, and for
many years my father had he truly been. My surprise at meeting him
on such a moor—on such a day—was but momentary, for I knew that
he was a shepherd who cared not for the winter’s wrath. As he
stopped to take my hand kindly into his, and to give his blessing to
his long-expected visitor, the wind fell calm—the whole face of the
sky was softened, and brightness, like a smile, went over the blushing
and crimson snow. The very elements seemed then to respect the
hoary head of fourscore; and after our first greeting was over, when I
looked around, in my affection, I felt how beautiful was winter.
“I am going,” said he, “to visit a man at the point of death; a man
whom you cannot have forgotten; whose head will be missed in the
kirk next Sabbath by all my congregation; a devout man, who feared
God all his days, and whom, on this awful trial, God will assuredly
remember. I am going, my son, to the Hazel Glen.”
I knew well in childhood that lonely farmhouse, so far off among
the beautiful wild green hills, and it was not likely that I had
forgotten the name of its possessor. For six years’ Sabbaths I had
seen the Elder in his accustomed place beneath the pulpit, and, with
a sort of solemn fear, had looked on his steadfast countenance during
sermon, psalm, and prayer. On returning to the scenes of my infancy,
I now met the pastor going to pray by his deathbed; and, with the
privilege which nature gives us to behold, even in their last
extremity, the loving and the beloved, I turned to accompany him to
the house of sorrow, resignation, and death.
And now, for the first time, I observed walking close to the feet of
his horse, a little boy of about ten years of age, who kept frequently
looking up in the pastor’s face, with his blue eyes bathed in tears. A
changeful expression of grief, hope, and despair, made almost pale
cheeks that otherwise were blooming in health and beauty; and I
recognised, in the small features and smooth forehead of childhood,
a resemblance to the aged man whom we understood was now lying
on his death-bed. “They had to send his grandson for me through the
snow, mere child as he is,” said the minister to me, looking tenderly
on the boy; “but love makes the young heart bold—and there is One
who tempers the wind to the shorn lamb.”
I again looked on the fearless child with his rosy cheeks, blue eyes,
and yellow hair, so unlike grief or sorrow, yet now sobbing aloud as if
his heart would break. “I do not fear but that my grandfather will yet
recover, as soon as the minister has said one single prayer by his
bedside. I had no hope, or little, as I was running by myself to the
manse over hill after hill, but I am full of hopes, now that we are
together; and oh! if God suffers my grandfather to recover, I will lie
awake all the long winter nights blessing Him for His mercy. I will
rise up in the middle of the darkness, and pray to Him in the cold on
my naked knees!” and here his voice was choked, while he kept his
eyes fixed, as if for consolation and encouragement, on the solemn
and pitying countenance of the kind-hearted pious old man.
We soon left the main road, and struck off through scenery that,
covered as it was with the bewildering snow, I sometimes dimly and
sometimes vividly remembered; our little guide keeping ever a short
distance before us, and with a sagacity like that of instinct, showing
us our course, of which no trace was visible, save occasionally his
own little footprints as he had been hurrying to the manse.
After crossing, for several miles, morass and frozen rivulet, and
drifted hollow, with here and there the top of a stone-wall peeping
through the snow, or the more visible circle of a sheep-bucht, we
descended into the Hazel-glen, and saw before us the solitary house
of the dying Elder.
A gleam of days gone by came suddenly over my soul. The last time
that I had been in this glen was on a day of June, fifteen years before,
—a holiday, the birthday of the king. A troop of laughing schoolboys,
headed by our benign pastor, we danced over the sunny braes, and
startled the linnets from their nests among the yellow broom.
Austere as seemed to us the Elder’s Sabbath face when sitting in the
kirk, we schoolboys knew that it had its week-day smiles, and we flew
on the wings of joy to our annual festival of curds and cream in the
farm-house of that little sylvan world. We rejoiced in the flowers and
the leaves of that long, that interminable summer day; its memory
was with our boyish hearts from June to June; and the sound of that
sweet name, “Hazel Glen,” often came upon us at our tasks, and
brought too brightly into the school-room the pastoral imagery of
that mirthful solitude.
As we now slowly approached the cottage through a deep snow-
drift, which the distress within had prevented the household from
removing, we saw peeping out from the door, brothers and sisters of
our little guide, who quickly disappeared, and then their mother
showed herself in their stead, expressing by her raised eyes, and
arms folded across her breast, how thankful she was to see at last the
pastor, beloved in joy and trusted in trouble.
Soon as the venerable old man dismounted from his horse, our
active little guide led it away into the humble stable, and we entered
the cottage. Not a sound was heard but the ticking of the clock. The
matron, who had silently welcomed us at the door, led us, with
suppressed sighs and a face stained with weeping, into her father’s
sick room, which even in that time of sore distress was as orderly as
if health had blessed the house. I could not help remarking some old
china ornaments on the chimneypiece, and in the window was an
ever-blowing rose-tree, that almost touched the lowly roof, and
brightened that end of the apartment with its blossoms. There was
something tasteful in the simple furniture; and it seemed as if grief
could not deprive the hand of that matron of its careful elegance.
Sickness, almost hopeless sickness, lay there, surrounded with the
same cheerful and beautiful objects which health had loved; and she,
who had arranged and adorned the apartment in her happiness, still
kept it from disorder and decay in her sorrow.
With a gentle hand she drew the curtain of the bed, and there,
supported by pillows as white as the snow that lay without, reposed
the dying Elder. It was plain that the hand of God was upon him, and
that his days on the earth were numbered.
He greeted his minister with a faint smile, and a slight inclination
of the head—for his daughter had so raised him on the pillows, that
he was almost sitting up in his bed. It was easy to see that he knew
himself to be dying, and that his soul was prepared for the great
change; yet, along with the solemn resignation of a Christian who
had made his peace with God and his Saviour, there was blended on
his white and sunken countenance an expression of habitual
reverence for the minister of his faith; and I saw that he could not
have died in peace without that comforter to pray by his death-bed.
A few words sufficed to tell who was the stranger;—and the dying
man, blessing me by name, held out to me his cold shrivelled hand,
in token of recognition. I took my seat at a small distance from the
bedside, and left a closer station for those who were more dear. The
pastor sat down near his head; and, by the bed, leaning on it with
gentle hands, stood that matron, his daughter-in-law—a figure that
would have graced and sainted a higher dwelling, and whose native
beauty was now more touching in its grief. But religion upheld her
whom nature was bowing down. Not now for the first time were the
lessons taught by her father to be put into practice, for I saw that she
was clothed in deep mourning and she behaved like the daughter of a
man whose life had been not only irreproachable but lofty, with fear
and hope fighting desperately but silently in the core of her pure and
pious heart.
While we thus remained in silence, the beautiful boy, who, at the
risk of his life, had brought the minister of religion to the bedside of
his beloved grandfather, softly and cautiously opened the door, and
with the hoar-frost yet unmelted on his bright glistering ringlets,
walked up to the pillow, evidently no stranger there. He no longer
sobbed—he no longer wept—for hope had risen strongly within his
innocent heart, from the consciousness of love so fearlessly exerted,
and from the presence of the holy man in whose prayers he trusted,
as in the intercession of some superior and heavenly nature. There
he stood, still as an image in his grandfather’s eyes, that, in their
dimness, fell upon him with delight. Yet, happy as was the trusting
child, his heart was devoured by fear, and he looked as if one word
might stir up the flood of tears that had subsided in his heart. As he
crossed the dreary and dismal moors, he had thought of a corpse, a
shroud, and a grave; he had been in terror, lest death should strike in
his absence the old man, with whose gray hairs he had so often
played; but now he saw him alive, and felt that death was not able to
tear him away from the clasps, and links, and fetters of his
grandchild’s embracing love.
“If the storm do not abate,” said the sick man, after a pause, “it will
be hard for my friends to carry me over the drifts to the kirkyard.”
This sudden approach to the grave struck, as with a bar of ice, the
heart of the loving boy; and, with a long deep sigh, he fell down with
his face like ashes on the bed, while the old man’s palsied right hand
had just strength to lay itself upon his head. “Blessed be thou, my
little Jamie, even for His own name’s sake who died for us on the
tree!” The mother, without terror, but with an averted face, lifted up
her loving-hearted boy, now in a dead fainting-fit, and carried him
into an adjoining room, where he soon revived. But that child and
the old man were not to be separated. In vain he was asked to go to
his brothers and sisters;—pale, breathless, and shivering, he took his
place as before, with eyes fixed on his grandfather’s face, but neither
weeping nor uttering a word. Terror had frozen up the blood of his
heart; but his were now the only dry eyes in the room; and the pastor
himself wept—albeit the grief of fourscore is seldom vented in tears.
“God has been gracious to me, a sinner,” said the dying man.
“During thirty years that I have been an elder in your kirk, never
have I missed sitting there one Sabbath. When the mother of my
children was taken from me—it was on a Tuesday she died, and on
Saturday she was buried—we stood together when my Alice was let
down into the narrow house made for all living; on the Sabbath I
joined in the public worship of God: she commanded me to do so the
night before she went away. I could not join in the psalm that
Sabbath, for her voice was not in the throng. Her grave was covered
up, and grass and flowers grew there; so was my heart; but thou,
whom, through the blood of Christ, I hope to see this night in
Paradise, knowest that, from that hour to this day, never have I
forgotten thee!”
The old man ceased speaking, and his grandchild, now able to
endure the scene (for strong passion is its own support), glided softly
to a little table, and bringing a cup in which a cordial had been
mixed, held it in his small soft hands to his grandfather’s lips. He
drank, and then said, “Come closer to me, Jamie, and kiss me for
thine own and thy father’s sake;” and as the child fondly pressed his
rosy lips on those of his grandfather, so white and withered, the tears
fell over all the old man’s face, and then trickled down on the golden
head of the child, at last sobbing in his bosom.
“Jamie, thy own father has forgotten thee in thy infancy, and me in
my old age; but, Jamie, forget not thou thy father nor thy mother, for
that thou knowest and feelest is the commandment of God.”
The broken-hearted boy could give no reply. He had gradually
stolen closer and closer unto the old loving man, and now was lying,
worn out with sorrow, drenched and dissolved in tears, in his
grandfather’s bosom. His mother had sunk down on her knees and
hid her face with her hands. “Oh! if my husband knew but of this—he
would never, never desert his dying father!” and I now knew that the
Elder was praying on his death-bed for a disobedient and wicked
son.
At this affecting time the minister took the family Bible on his
knees, and said, “Let us sing to the praise and glory of God, part of
the fifteenth psalm;” and he read, with a tremulous and broken voice,
those beautiful verses:—
“Within thy tabernacle, Lord,
Who shall abide with thee?
And in Thy high and holy hill
Who shall a dweller be?
The man that walketh uprightly,
And worketh righteousness,
And as he thinketh in his heart,
So doth he truth express.”
By D. M. Moir, M.D.
How then was the Devil drest?
He was in his Sunday’s best;
His coat was red, and his breeches were blue,
With a hole behind, where his tail came through.
About this time[8] there arose a great sough and surmise that some
loons were playing false with the kirkyard, howking up the bodies
from their damp graves, and hurling them away to the college.
Words canna describe the fear, and the dool, and the misery it
caused. All flocked to the kirk yett; and the friends of the newly
buried stood by the mools, which were yet dark, and the brown,
newly-cast divots, that had not yet ta’en root, looking with mournful
faces, to descry any tokens of sinking in.
8. See ante, “Benjie’s Christening,” page 214.
I’ll never forget it. I was standing by when three young lads took
shools, and, lifting up the truff, proceeded to howk down to the
coffin, wherein they had laid the gray hairs of their mother. They
looked wild and bewildered like, and the glance of their een was like
that of folk out of a mad-house; and none dared in the world to have
spoken to them. They didna even speak to ane anither; but wrought
on wi’ a great hurry till the spades struck on the coffin-lid—which
was broken. The dead-claithes were there huddled a’thegither in a
nook, but the dead was gane. I took haud o’ Willie Walker’s arm, and
looked down. There was a cauld sweat all ower me;—losh me! but I
was terribly frighted and eerie. Three mair graves were opened, and
a’ just alike, save and except that of a wee unkirstened wean, which
was aff bodily, coffin and a’.
There was a burst of righteous indignation throughout the parish;
nor without reason. Tell me that doctors and graduates maun hae the
dead; but tell it not to Mansie Wauch, that our hearts maun be
trampled in the mire of scorn, and our best feelings laughed at, in
order that a bruise may be properly plaistered up, or a sair head
cured. Verily, the remedy is waur than the disease.
But what remead? It was to watch in the session-house, with
loaded guns, night about, three at a time. I never likit to gang into
the kirkyard after darkening, let-a-be to sit there through a lang
winter night, windy and rainy, it may be, wi’ nane but the dead
around us. Save us! it was an unco thought, and garred a’ my flesh
creep; but the cause was gude,—my spirit was roused, and I was
determined no to be dauntoned.
I counted and counted, but the dread day at length came, and I
was summonsed. All the leivelang afternoon, when ca’ing the needle
upon the brod, I tried to whistle Jenny Nettles, Niel Gow, and ither
funny tunes, and whiles crooned to mysel between hands; but my
consternation was visible, and a’ wadna do.
It was in November, and the cauld glimmering sun sank behind
the Pentlands. The trees had been shorn of their frail leaves; and the
misty night was closing fast in upon the dull and short day; but the
candles glittered at the shop windows, and leery-light-the-lamps was
brushing about wi’ his ladder in his oxter, and bleezing flamboy
sparking out behind him. I felt a kind of qualm of faintness and
down-sinking about my heart and stomach, to the dispelling of which
I took a thimbleful of spirits, and, tying my red comforter about my
neck, I marched briskly to the session-house. A neighbour (Andrew
Goldie, the pensioner) lent me his piece, and loaded it to me. He took
tent that it was only half-cock, and I wrapped a napkin round the
dog-head, for it was raining. No being acquaint wi’ guns, I keepit the
muzzle aye awa frae me; as it is every man’s duty no to throw his
precious life into jeopardy.
A furm was set before the session-house fire, which bleezed
brightly, nor had I ony thought that such an unearthly place could
have been made to look half so comfortable, either by coal or candle;
so my speerits rose up as if a weight had been ta’en aff them, and I
wondered in my bravery, that a man like me could be afeard of
onything. Nobody was there but a touzy, ragged, halflins callant of
thirteen (for I speired his age), wi’ a desperate dirty face, and lang
carroty hair, tearing a speldrin wi’ his teeth, which lookit lang and
sharp eneugh, and throwing the skin and lugs intil the fire.
We sat for amaist an hour thegither, cracking the best way we
could in sic a place; nor was onybody mair likely to cast up. The night
was now pit-mirk; the wind soughed amid the headstanes and
railings of the gentry (for we maun a’ dee); and the black corbies in
the steeple-holes cackled and crawed in a fearsome manner. A’ at
ance we heard a lonesome sound; and my heart began to play pit-pat
—my skin grew a’ rough, like a poukit chicken—and I felt as if I didna
ken what was the matter with me. It was only a false alarm, however,
being the warning of the clock; and in a minute or twa thereafter the
bell struck ten. Oh, but it was a lonesome and dreary sound! Every
chap gaed through my breast like the dunt of a forehammer.
Then up and spak the red headed laddie: “It’s no fair; anither
should hae come by this time. I wad rin awa hame, only I’m
frightened to gang out my lane. Do ye think the doup o’ that candle
wad carry in my cap?”
“Na, na, lad; we maun bide here, as we are here now. Leave me
alane! Lord save us! and the yett lockit, and the bethrel sleepin’ wi’
the key in his breek-pouches! We canna win out now, though we
would,” answered I, trying to look brave, though half frightened out
of my seven senses. “Sit down, sit down; I’ve baith whisky and porter
wi’ me. Hae, man, there’s a cauker to keep your heart warm; and set
down that bottle,” quoth I, wiping the sawdust aff it with my hand,
“to get a toast; I’se warrant it for Deacon Jaffrey’s best brown stout.”
The wind blew higher, and like a hurricane; the rain began to fall
in perfect spouts; the auld kirk rumbled, and rowed, and made a sad
soughing; and the bourtree tree behind the house, where auld
Cockburn, that cuttit his throat, was buried, creakit and crazed in a
frightful manner; but as to the roaring of the troubled waters, and
the bumming in the lum-head, they were past a’ power of
description. To make bad worse, just in the heart of the brattle, the
grating sound of the yett turning on its rusty hinges was but too
plainly heard. What was to be done? I thought of our baith running
away; and then of our locking oursels in, and firing through the door;
but wha was to pull the trigger?
Gudeness watch ower us! I tremble yet when I think on’t. We were
perfectly between the deil and the deep sea—either to stand and fire
our gun, or rin and be shot at. It was really a hang choice. As I stood
swithering and shaking, the laddie ran to the door, and thrawing
round the key, clapped his back till’t. Oh! how I lookit at him, as he
stude, for a gliff, like a magpie hearkening wi’ his lug cockit up, or
rather like a terrier watching a rotten.
“They’re coming! they’re coming!” he cried out; “cock the piece, ye
sumph,” while the red hair rose up from his pow like feathers;
“they’re coming, I hear them tramping on the gravel!” Out he
stretched his arms against the wall, and brizzed his back against the
door like mad; as if he had been Samson pushing over the pillars in
the house of Dagon. “For the Lord’s sake, prime the gun,” he cried
out, “or our throats will be cut frae lug to lug, before we can say Jack
Robinson! See that there’s priming in the pan!”
I did the best I could; but my hale strength could hardly lift up the
piece, which waggled to and fro like a cock’s tail on a rainy day; my
knees knockit against ane anither, and though I was resigned to dee
—I trust I was resigned to dee—’od, but it was a frightfu’ thing to be
out of ane’s bed, and to be murdered in an auld session-house, at the
dead hour of night, by unyearthly resurrection-men—or rather let me
call them devils incarnate—wrapt up in dreadnoughts, wi’ blackit
faces, pistols, big sticks, and other deadly weapons.
A snuff-snuffing was heard; and through below the door I saw a
pair of glancing black een. ’Od, but my heart nearly loupit aff the bit
—a snouff and a gur—gurring, and ower a’ the plain tramp of a man’s
heavy tackets and cuddy-heels amang the gravel. Then cam a great
slap like thunder on the wall; and the laddie quitting his grip, fell
down, crying, “Fire, fire!—murder! holy murder!”
“Wha’s there?” growled a deep rough voice; “open—I’m a friend.”
I tried to speak, but could not; something like a halfpenny roll was
sticking in my throat, so I tried to cough it up, but it wadna come.
“Gie the pass-word, then,” said the laddie, staring as if his een wad
loupen out; “gie the pass-word!”
First cam a loud whussle, and then “Copmahagen,” answered the
voice. Oh! what a relief! The laddie started up like ane crazy wi’ joy.
“Ou! ou!” cried he, thrawing round the key, and rubbing his hands,
“by jingo! it’s the bethrel—it’s the bethrel—it’s auld Isaac himsel!”
First rushed in the dog, and then Isaac, wi’ his glazed hat, slouched
ower his brow, and his horn bowet glimmering by his knee. “Has the
French landit, do ye think? Losh keep us a’!” said he, wi’ a smile on
his half-idiot face (for he was a kind of a sort of a natural, wi’ an
infirmity in his leg). “’Od sauf us, man, put by your gun. Ye dinna
mean to shoot me, do ye? What are ye aboot here wi’ the door lockit?
I just keppit four resurrectioners louping ower the wa’.”
“Gude guide us!” I said, taking a long breath to drive the blude frae
my heart, and something relieved by Isaac’s company. “Come now,
Isaac, ye’re just giein’ us a fright. Isn’t that true, Isaac?”
“Yes, I’m joking,—and what for no? But they might have been, for
onything ye wad hae hindered them to the contrair, I’m thinking. Na,
na, ye maunna lock the door; that’s no fair play.”
When the door was put ajee, and the furm set fornent the fire, I
gied Isaac a dram to keep his heart up on sic a cauld, stormy night.
’Od, but he was a droll fallow, Isaac. He sung and leuch as if he had
been boozing in Lucky Tamson’s, wi’ some of his drucken cronies.
Fient a hair cared he about auld kirks, or kirkyards, or vouts, or
through-stanes, or dead folk in their winding-sheets, wi’ the wet
grass growing ower them; and at last I began to brighten up a wee
mysel; so when he had gone ower a good few funny stories, I said to
him, quoth I, “Mony folk, I daresay, mak mair noise about their
sitting up in a kirkyard than it’s a’ worth. There’s naething here to
harm us.”
“I beg to differ wi’ ye there,” answered Isaac, taking out his horn
mull from his coat pouch, and tapping on the lid in a queer style—“I
could gie anither version of that story. Did ye no ken of three young
doctors—Eirish students—alang wi’ some resurrectioners, as waff
and wild as themselves, firing shottie for shottie wi’ the guard at
Kirkmabreck, and lodging three slugs in ane o’ their backs, forbye
firing a ramrod through anither ane’s hat?”