(Download PDF) Go Cookbook Expert Solutions For Commonly Needed Go Tasks First Early Release Sau Sheong Chang Ebook Online Full Chapter

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

Go Cookbook: Expert Solutions for

Commonly Needed Go Tasks (First


Early Release) Sau Sheong Chang
Visit to download the full and correct content document:
https://ebookmeta.com/product/go-cookbook-expert-solutions-for-commonly-needed-
go-tasks-first-early-release-sau-sheong-chang/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Go Cookbook: Expert Solutions for Commonly Needed Go


Tasks 1st Edition Sau Sheong Chang

https://ebookmeta.com/product/go-cookbook-expert-solutions-for-
commonly-needed-go-tasks-1st-edition-sau-sheong-chang/

Learning Go, 2nd Edition (Early Release) Jon Bodner

https://ebookmeta.com/product/learning-go-2nd-edition-early-
release-jon-bodner/

Learning Go 2nd Edition 4th Early Release Jon Bodner

https://ebookmeta.com/product/learning-go-2nd-edition-4th-early-
release-jon-bodner/

Efficient Go: Data Driven Performance Optimization


(Fourth Early Release) Bartlomiej Plotka

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/

GitOps Cookbook (Third Early Release) Natale Vinto

https://ebookmeta.com/product/gitops-cookbook-third-early-
release-natale-vinto/

Azure Cookbook (4th Early Release) Fourth Early


Release: 2023-06-22 Edition Reza Salehi

https://ebookmeta.com/product/azure-cookbook-4th-early-release-
fourth-early-release-2023-06-22-edition-reza-salehi/

Let s Go Let s Go Let s Go 1st Edition Cleo Qian

https://ebookmeta.com/product/let-s-go-let-s-go-let-s-go-1st-
edition-cleo-qian-2/

Let s Go Let s Go Let s Go 1st Edition Cleo Qian

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.

Sau Sheong Chang


Go Cookbook
by Sau Sheong Chang
Copyright © 2023 Sau Sheong Chang. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North,
Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales
promotional use. Online editions are also available for most titles
(http://oreilly.com). For more information, contact our
corporate/institutional sales department: 800-998-9938 or
corporate@oreilly.com.
Acquisitions Editor: Suzanne McQuade
Development Editor: Shira Evans
Production Editor: Elizabeth Faerm
Copyeditor: TO COME
Proofreader: TO COME
Indexer: TO COME
Interior Designer: David Futato
Cover Designer: Karen Montgomery
Illustrator: Kate Dullea
July 2023: First Edition
Revision History for the Early Release
2022-02-01: First Release
See http://oreilly.com/catalog/errata.csp?isbn=9781098122119 for
release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Go
Cookbook, the cover image, and related trade dress are trademarks
of O’Reilly Media, Inc.
The views expressed in this work are those of the author, and do not
represent the publisher’s views. While the publisher and the author
have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and
the author disclaim all responsibility for errors or omissions,
including without limitation responsibility for damages resulting from
the use of or reliance on this work. Use of the information and
instructions contained in this work is at your own risk. If any code
samples or other technology this work contains or describes is
subject to open source licenses or the intellectual property rights of
others, it is your responsibility to ensure that your use thereof
complies with such licenses and/or rights.
978-1-098-12205-8
[TO COME]
Chapter 1. General
Input/Output Recipes

A NOTE FOR EARLY RELEASE READERS


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.
This will be the 8th chapter of the final book.
If you have comments about how we might improve the content and/or
examples in this book, or if you notice missing material within this chapter,
please reach out to the editor at sevans@oreilly.com.

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.

1.1 Reading from an Input

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.

type Reader interface {


Read(p []byte) (n int, err error)
}

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.

bytes = make([]byte, 1024)


reader.Read(bytes)

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.

bytes, err := os.ReadAll(reader)

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.

str := “My String Data”


reader := strings.NewReader(str)

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.

type Writer interface {


Write(p []byte) (n int, err error)
}

When you call Write on an io.Writer you are writing the bytes
to the underlying data stream.

bytes = []byte("Hello World")


writer.Write(bytes)

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"

The bytes.Buffer struct is a Writer (it implements the Write


function) so you can easily create one, and pass it to the
fmt.Fprintf function, which takes in an io.Writer as its first
parameter. The fmt.Fprintf function writes data on to the buffer
and you can extract the data out from it later.
This pattern of using a writer to pass data around by writing to it,
then extracting it out later is quite common in Go. Another example
is in the HTTP handlers with the http.ResponseWriter.

func myHandler(w http.ResponseWriter, r *http.Request) {


w.Write([]bytes("Hello World"))
}

Here, we write to the ResponseWriter and the data will be taken


as input to be sent back to the browser.

1.3 Copying from a Reader to a Writer

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.

// using a random 1MB test file


var url string =
"http://speedtest.ftp.otenet.gr/files/test1Mb.db"

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)
}

When we use http.Get to download a file we get a


http.Response struct back. The content of the file is in the Body
variable of the http.Response struct, which is a
io.ReadCloser. A ReadCloser is just an interface that groups a
Reader and a Closer so we here we can treat it just like a reader.
We use the os.ReadAll function to read the data from Body and
then os.WriteFile to write it to file.
That’s simple enough but let’s take a look at the performance of the
function. We use the benchmarking capabilities that’s part of the
standard Go tools to do this. First we create a test file, just like any
other test files.

package main

import "testing"
func BenchmarkReadWrite(b *testing.B) {
readWrite()
}

In this test file instead of a function that starts with Testxxx we


create a function that starts with Benchmarkxxx which takes in a
parameter b that is a reference to testing.B.
The benchmark function is very simple, we just call our readWrite
function. Let’s run it from the command line and see how we
perform.

$ go test -bench=. -benchmem

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

We ran a benchmark test for a function that downloaded a 1 MB file.


The test only ran one time, and it took 1.99 seconds. It also took
5.89 MB of memory and 219 distinct memory allocations.
As you can see, it’s quite an expensive operation just to download a
1 MB file. After all, it takes almost 6 MB of memory to download a 1
MB file. Alternatively we can use io.Copy to do pretty much the
same thing for a lot less memory.
func copy() {
r, err := http.Get(url)
if err != nil {
log.Println("Cannot get from URL", err)
}
defer r.Body.Close()
file, _ := os.Create("copy.data")
defer file.Close()
writer := bufio.NewWriter(file)
io.Copy(writer, r.Body)
writer.Flush()
}

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"

func BenchmarkReadWrite(b *testing.B) {


readWrite()
}

func BenchmarkCopy(b *testing.B) {


copy()
}

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.

1.4 Reading from a Text File

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.

Read everything at one go


The easiest way to read a text file is to use os.ReadFile. Let’s say
we want to read from a text file named data.txt.

hello world!

To read the file, just give the name of the file as a parameter to
os.ReadFile and you’re done!

data, err := os.ReadFile("data.txt")


if err != nil {
log.Println("Cannot read file:", err)
}
fmt.Println(string(data))

This will print out hello world!.

Opening a file and reading from it


Reading a file by opening it and then doing a read on it is more
flexible but takes a few more steps. First, you need to open the file.

// open the file


file, err := os.Open("data.txt")
if err != nil {
log.Println("Cannot open file:", err)
}
// close the file when we are done with it
defer file.Close()

This can be done using os.Open, which returns a File struct in


read-only. If you want to open it in different modes, you can use
os.OpenFile. It’s good practice to set up the file for closing using
the defer keyword, which will close the file just before the function
returns.
Next, we need to create a byte array to store the data.

// get some info from the file


stat, err := file.Stat()
if err != nil {
log.Println("Cannot read file stats:", err)
}
// create the byte array to store the read data
data := make([]byte, stat.Size())

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.

// read the file


bytes, err := file.Read(data)
if err != nil {
log.Println("Cannot read file:", err)
}
fmt.Printf("Read %d bytes from file\n", bytes)
fmt.Println(string(data))

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.

Read 13 bytes from file


Hello World!

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.

Writing to a file at one go


Given the data, you can write to a file at one go using
os.WriteFile.

data := []byte("Hello World!\n")

err := os.WriteFile("data.txt", data, 0644)


if err != nil {
log.Println("Cannot write to file:", err)
}

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.

data := []byte("Hello World!\n")


// write to file and read from file using the File struct
file, err := os.Create("data.txt")
if err != nil {
log.Println("Cannot create file:", err)
}
defer file.Close()

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.

bytes, err := file.Write(data)


if err != nil {
log.Println("Cannot write to file:", err)
}
fmt.Printf("Wrote %d bytes to file\n", bytes)

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())

We need to know because the temp files created by


os.CreateTemp will be created there. Normally we wouldn’t care,
but because we’re trying to analyse step by step how the temp files
get created, we want to know exactly where it is. When we execute
this statement, we should see something like this.

/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.

tmpdir, err := os.MkdirTemp(os.TempDir(), "mytmpdir_*")


if err != nil {
log.Println("Cannot create temp directory:", err)
}
defer os.RemoveAll(tmpdir)

The first parameter to os.MkdirTemp is the temporary directory


and the second parameter is a pattern string. The function will apply
a random string to replace the * in the pattern string. It is also a
good practise to defer the cleaning up of the temporary directory by
remove it using os.RemoveAll.
Next we’re creating the actual temporary file using
os.CreateTemp, passing it the temporary directory we just created
and also a pattern string for the file name, which works the same as
as the temporary directory.

tmpfile, err := os.CreateTemp(tmpdir, "mytmp_*")


if err != nil {
log.Println("Cannot create temp file:", err)
}

With that, we have a file and everything else works the same way as
any other file.

data := []byte("Some random stuff for the temporary file")


_, err = tmpfile.Write(data)
if err != nil {
log.Println("Cannot write to temp file:", err)
}
err = tmpfile.Close()
if err != nil {
log.Println("Cannot close temp file:", err)
}
If you didn’t choose to put your temporary files into a separate
directory (which you delete and also everything in it when you’re
done), you can use os.Remove with the temporary file name like
this.

defer os.Remove(tmpfile.Name())
Chapter 2. CSV Recipes

A NOTE FOR EARLY RELEASE READERS


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.
This will be the 9th chapter of the final book.
If you have comments about how we might improve the content and/or
examples in this book, or if you notice missing material within this chapter,
please reach out to the editor at sevans@oreilly.com.

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.

2.1 Reading a CSV File

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.

file, err := os.Open("users.csv")


if err != nil {
log.Println("Cannot open CSV file:", err)
}
defer file.Close()
reader := csv.NewReader(file)
rows, err := reader.ReadAll()
if err != nil {
log.Println("Cannot read CSV file:", err)
}
First, we open the file using os.Open. This creates an os.File
struct (which is an io.Reader) that we can use as a parameter to
csv.NewReader. The csv.NewReader creates a new
csv.Reader struct that can be used to read data from the CSV file.
With this CSV reader, we can use ReadAll to read all the data in
the file and return a 2D array of strings [][]string.
A 2 dimensional array of strings? You might be surprised, what if the
CSV row item is an integer? Or a boolean or any other types? You
should remember CSV files are text files, so there is really no way for
you to differentiate if a value is anything else other than a string. In
other words, all values are assumed to be string, and if you think
otherwise you need to cast it to something else.

Unmarshalling CSV data into structs


Problem
You want to unmarshal CSV data into structs instead of a 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.

type User struct {


Id int
firstName string
lastName string
email string
}

If you want to unmarshal the data in the 2D array of strings to the


User struct, you need to convert each item yourself.

var users []User


for _, row := range rows {
id, _ := strconv.ParseInt(row[0], 0, 0)
user := User{Id: int(id),
firstName: row[1],
lastName: row[2],
email: row[3],
}
users = append(users, user)
}

In the example above, because the user ID is an integer, I used


strconv.ParseInt to convert the string into integer before using
it to create the User struct.
You see that at the end of the for loop you will have an array of User
structs. If you print that out, this is what you should see.

{0 first_name last_name email}


{1 Sausheong Chang sausheong@email.com}
{2 John Doe john@email.com}

2.2 Removing the Header Line

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.

file, err := os.Open("users.csv")


if err != nil {
log.Println("Cannot open CSV file:", err)
}
defer file.Close()
reader := csv.NewReader(file)
reader.Read() // use Read to remove the first line
rows, err := reader.ReadAll()
if err != nil {
log.Println("Cannot read CSV file:", err)
}

This will give us something like this:

{1 Sausheong Chang sausheong@email.com}


{2 John Doe john@email.com}

2.3 Using Different Delimiters

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

What we just need to do is the set the Comma in the csv.Reader


struct we created earlier and you read the file as before.

file, err := os.Open("users2.csv")


if err != nil {
log.Println("Cannot open CSV file:", err)
}
defer file.Close()
reader := csv.NewReader(file)
reader.Comma = ';' // change Comma to the delimiter in the
file
rows, err := reader.ReadAll()
if err != nil {
log.Println("Cannot read CSV file:", err)
}

2.4 Ignoring Rows

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

To enable commenting, just set the Comment variable in the


csv.Reader struct that we got from csv.NewReader.

file, err := os.Open("users.csv")


if err != nil {
log.Println("Cannot open CSV file:", err)
}
defer file.Close()
reader := csv.NewReader(file)
reader.Comment = '#' // lines that start with this will be
ignored
rows, err := reader.ReadAll()
if err != nil {
log.Println("Cannot read CSV file:", err)
}

When you run this, you’ll see:

{0 first_name last_name email}


{1 Sausheong Chang sausheong@email.com}
2.5 Writing CSV Files

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).

file, err := os.Create("new_users.csv")


if err != nil {
log.Println("Cannot create CSV file:", err)
}
defer file.Close()

The data to write to the file needs to be in a 2 dimensional array of


strings. Remember, if you don’t have the data as a string, just
convert it into a string before you do this. Create a csv.Writer
struct with the file. After that you can call WriteAll on the writer
and the file will be created. This writes all the data in your 2
dimensional string array into the file.

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)
}

2.6 Writing to File One Row at a Time

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.”

The small congregation sang the noble hymn of the psalmist to


“plaintiff Martyrs, worthy of the name.” The dying man himself, ever
and anon, joined in the holy music; and when it feebly died away on
his quivering lips, he continued still to follow the tune with the
motion of his withered hand, and eyes devoutly and humbly lifted up
to heaven. Nor was the sweet voice of his loving grandchild unheard;
as if the strong fit of deadly passion had dissolved in the music, he
sang with a sweet and silvery voice, that, to a passer-by, had seemed
that of perfect happiness—a hymn sung in joy upon its knees by
gladsome childhood before it flew out among the green hills, to quiet
labour or gleesome play. As that sweetest voice came from the bosom
of the old man, where the singer lay in affection, and blended with
his own so tremulous, never had I felt so affectingly brought before
me the beginning and the end of life, the cradle and the grave.
Ere the psalm was yet over, the door was opened, and a tall fine-
looking man entered, but with a lowering and dark countenance,
seemingly in sorrow, in misery, and remorse. Agitated, confounded,
and awe-struck by the melancholy and dirge-like music, he sat down
on a chair, and looked with a ghastly face towards his father’s death-
bed. When the psalm ceased, the Elder said with a solemn voice, “My
son, thou art come in time to receive thy father’s blessing. May the
remembrance of what will happen in this room before the morning
again shine over the Hazel Glen win thee from the error of thy ways!
Thou art here, to witness the mercy of thy God and thy Saviour,
whom thou hast forgotten.”
The minister looked, if not with a stern, yet with an upbraiding
countenance, on the young man, who had not recovered his speech,
and said, “William! for three years past your shadow has not
darkened the door of the house of God. They who fear not the
thunder may tremble at the still small voice; now is the hour for
repentance, that your father’s spirit may carry up to heaven tidings of
a contrite soul saved from the company of sinners!”
The young man, with much effort, advanced to the bedside, and at
last found voice to say, “Father, I am not without the affections of
nature, and I hurried home as soon as I heard that the minister had
been seen riding towards our house. I hope that you will yet recover,
and if I have ever made you unhappy, I ask your forgiveness; for
though I may not think as you do on matters of religion, I have a
human heart. Father! I may have been unkind, but I am not cruel. I
ask your forgiveness.”
“Come nearer to me, William; kneel down by the bedside, and let
my hand find the head of my beloved son—for blindness is coming
fast upon me. Thou wert my first-born, and thou art my only living
son. All thy brothers and sisters are lying in the kirkyard, beside her
whose sweet face thine own, William, did once so much resemble.
Long wert thou the joy, the pride of my soul—ay, too much the pride,
for there was not in all the parish such a man, such a son, as my own
William. If thy heart has since been changed, God may inspire it
again with right thoughts. Could I die for thy sake—could I purchase
thy salvation with the outpouring of thy father’s blood—but this the
Son of God has done for thee, who hast denied Him! I have sorely
wept for thee—ay, William, when there was none near me—even as
David wept for Absalom, for thee, my son, my son!”
A long deep groan was the only reply; but the whole body of the
kneeling man was convulsed; and it was easy to see his sufferings, his
contrition, his remorse, and his despair. The pastor said, with a
sterner voice and austerer countenance than were natural to him,
“Know you whose hand is now lying on your rebellious head? But
what signifies the word father to him who has denied God, the Father
of us all?”—“Oh! press him not so hardly,” said the weeping wife,
coming forward from a dark corner of the room, where she had tried
to conceal herself in grief, fear, and shame. “Spare, oh! spare my
husband—he has ever been kind to me;” and with that she knelt
down beside him, with her long, soft, white arms mournfully and
affectionately laid across his neck. “Go thou, likewise, my sweet little
Jamie,” said the Elder, “go even out of my bosom, and kneel down
beside thy father and thy mother, so that I may bless you all at once,
and with one yearning prayer.” The child did as that solemn voice
commanded, and knelt down somewhat timidly by his father’s side;
nor did that unhappy man decline encircling with his arm the child
too much neglected, but still dear to him as his own blood, in spite of
the deadening and debasing influence of infidelity.
“Put the Word of God into the hands of my son, and let him read
aloud to his dying father the 25th, 26th, and 27th verses of the
eleventh chapter of the Gospel according to St John.” The pastor
went up to the kneelers, and, with a voice of pity, condolence, and
pardon, said, “There was a time when none, William, could read the
Scriptures better than couldst thou—can it be that the son of my
friend hath forgotten the lessons of his youth?” He had not forgotten
them; there was no need for the repentant sinner to lift up his eyes
from the bedside. The sacred stream of the Gospel had worn a
channel in his heart, and the waters were again flowing. With a
choked voice he said, “Jesus said unto her, I am the Resurrection and
the Life: he that believeth in me, though he were dead, yet shall he
live: and whosoever liveth and believeth in me, shall never die.
Believest thou this? She saith unto him, Yea, Lord; I believe that thou
art the Christ, the Son of God, which should come into the world.”
“That is not an unbeliever’s voice,” said the dying man
triumphantly; “nor, William, hast thou an unbeliever’s heart. Say
that thou believest in what thou hast now read, and thy father will
die happy!”—“I do believe; and as thou forgivest me, so may I be
forgiven by my Father who is in heaven.”
The Elder seemed like a man suddenly inspired with a new life. His
faded eyes kindled—his pale cheeks glowed—his palsied hands
seemed to wax strong—and his voice was clear as that of manhood in
its prime. “Into Thy hands, O God, I commit my spirit!”—and so
saying, he gently sank back on his pillow; and I thought I heard a
sigh. There was then a long deep silence, and the father, and mother,
and child rose from their knees. The eyes of us all were turned
towards the white placid face of the figure now stretched in
everlasting rest; and without lamentations, save the silent
lamentations of the resigned soul, we stood around the “Death-bed
of the Elder.”
A HIGHLAND FEUD.

By Sir Walter Scott.

The principal possessors of the Hebrides were originally of the


name of MacDonald, the whole being under the government of a
succession of chiefs, who bore the name of Donald of the Isles, and
were possessed of authority almost independent of the kings of
Scotland. But this great family becoming divided into two or three
branches, other chiefs settled in some of the islands, and disputed
the property of the original proprietors. Thus, the MacLeods, a
powerful and numerous clan, who had extensive estates on the
mainland, made themselves masters, at a very early period, of a great
part of the large island of Skye, seized upon much of the Long Island,
as the isles of Lewis and Harris are called, and fought fiercely with
the MacDonalds and other tribes of the islands. The following is an
example of the mode in which these feuds were conducted:—
About the end of the sixteenth century, a boat, manned by one or
two of the MacLeods, landed in Eigg, a small island peopled by the
MacDonalds. They were at first hospitably received; but having been
guilty of some incivility to the young women of the island, it was so
much resented by the inhabitants, that they tied the MacLeods hand
and foot, and putting them on board of their own boat, towed it to
the sea, and set it adrift, leaving the wretched men, bound as they
were, to perish by famine, or by the winds and waves, as chance
should determine. But fate so ordered it, that a boat belonging to the
Laird of MacLeod fell in with that which had the captives on board,
and brought them in safety to the Laird’s castle of Dunvegan, in
Skye, where they complained of the injury which they had sustained
from the MacDonalds of Eigg. MacLeod, in great rage, put to sea
with his galleys, manned by a large body of his people, which the
men of Eigg could not entertain any rational hope of resisting.
Learning that their incensed enemy was approaching with superior
forces, and deep vows of revenge, the inhabitants, who knew they
had no mercy to expect at MacLeod’s hands, resolved, as the best
chance of safety in their power, to conceal themselves in a large
cavern on the sea-shore.
This place was particularly well-calculated for that purpose. The
entrance resembles that of a fox-earth, being an opening so small
that a man cannot enter save by creeping on hands and knees. A rill
of water falls from the top of the rock, and serves, or rather served at
the period we speak of, wholly to conceal the aperture. A stranger,
even when apprised of the existence of such a cave, would find the
greatest difficulty in discovering the entrance. Within, the cavern
rises to a great height, and the floor is covered with white dry sand. It
is extensive enough to contain a great number of people. The whole
inhabitants of Eigg, who, with their wives and families, amounted to
nearly two hundred souls, took refuge within its precincts.
MacLeod arrived with his armament, and landed on the island, but
could discover no one on whom to wreak his vengeance—all was
desert. The MacLeods destroyed the huts of the islanders, and
plundered what property they could discover; but the vengeance of
the chieftain could not be satisfied with such petty injuries. He knew
that the inhabitants must either have fled in their boats to one of the
islands possessed by the MacDonalds, or that they must be concealed
somewhere in Eigg. After making a strict but unsuccessful search for
two days, MacLeod had appointed the third to leave his anchorage,
when, in the gray of the morning, one of the seamen beheld, from the
deck of his galley, the figure of a man on the island. This was a spy
whom the MacDonalds, impatient of their confinement in the cavern,
had imprudently sent out to see whether MacLeod had retired or no.
The poor fellow, when he saw himself discovered, endeavoured, by
doubling after the manner of a hare or fox, to obliterate the track of
his footsteps, and prevent its being discovered where he had re-
entered the cavern. But all his art was in vain; the invaders again
landed, and tracked him to the entrance of the cavern.
MacLeod then summoned those who were within it, and called
upon them to deliver the individuals who had maltreated his men, to
be disposed of at his pleasure. The MacDonalds, still confident in the
strength of their fastness, which no assailant could enter but on
hands and knees, refused to surrender their clansmen.
MacLeod then commenced a dreadful work of indiscriminate
vengeance. He caused his people, by means of a ditch cut above the
top of the rock, to turn away the stream of water which fell over the
entrance of the precipice. This being done, the MacLeods collected
all the combustibles which could be found on the island, particularly
quantities of dry heather, piled them up against the aperture, and
maintained an immense fire for many hours, until the smoke,
penetrating into the inmost recesses of the cavern, stifled to death
every creature within. There is no doubt of the truth of this story,
dreadful as it is. The cavern is often visited by strangers; and I have
myself seen the place, where the bones of the murdered MacDonalds
still remain, lying as thick on the floor of the cave as in the charnel-
house of a church.
THE RESURRECTION MEN.

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.

Over the hill, and over the dale,


And he went over the plain:
And backward and forward he switched his tail,
As a gentleman switches his cane.
Coleridge.

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?”

You might also like