100% found this document useful (4 votes)
23 views

Go Systems Programming Master Linux and Unix system level programming with Go 1st Edition Mihalis Tsoukalos instant download

The document is a promotional overview of the book 'Go Systems Programming: Master Linux and Unix System Level Programming with Go' by Mihalis Tsoukalos, published by Packt Publishing. It includes links to various related eBooks and highlights the author's background and contributions to technical writing. The book covers a range of topics in systems programming using Go, including advanced features, file handling, and concurrency.

Uploaded by

pargaborykvf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
23 views

Go Systems Programming Master Linux and Unix system level programming with Go 1st Edition Mihalis Tsoukalos instant download

The document is a promotional overview of the book 'Go Systems Programming: Master Linux and Unix System Level Programming with Go' by Mihalis Tsoukalos, published by Packt Publishing. It includes links to various related eBooks and highlights the author's background and contributions to technical writing. The book covers a range of topics in systems programming using Go, including advanced features, file handling, and concurrency.

Uploaded by

pargaborykvf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Go Systems Programming Master Linux and Unix

system level programming with Go 1st Edition


Mihalis Tsoukalos download

https://ebookgate.com/product/go-systems-programming-master-
linux-and-unix-system-level-programming-with-go-1st-edition-
mihalis-tsoukalos/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

Linux system programming 1st Edition Robert Love

https://ebookgate.com/product/linux-system-programming-1st-
edition-robert-love/

Automating Linux and Unix System Administration 2nd


Edition Campi

https://ebookgate.com/product/automating-linux-and-unix-system-
administration-2nd-edition-campi/

UNIX systems programming communication concurrency and


threads 2nd printing Edition Kay A. Robbins

https://ebookgate.com/product/unix-systems-programming-
communication-concurrency-and-threads-2nd-printing-edition-kay-a-
robbins/

Programming Linux Games 1st Edition Loki Software

https://ebookgate.com/product/programming-linux-games-1st-
edition-loki-software/
Professional Parallel Programming with C Master
Parallel Extensions with NET 4 1st Edition Gaston
Hillar

https://ebookgate.com/product/professional-parallel-programming-
with-c-master-parallel-extensions-with-net-4-1st-edition-gaston-
hillar/

Let s Go 3 Workbook Let s Go Third Edition Ritsuko


Nakata

https://ebookgate.com/product/let-s-go-3-workbook-let-s-go-third-
edition-ritsuko-nakata/

Assembly Language Step by Step Programming with Linux


3rd Edition Edition Jeff Duntemann

https://ebookgate.com/product/assembly-language-step-by-step-
programming-with-linux-3rd-edition-edition-jeff-duntemann/

Go Cookbook Build modular readable and testable


applications in Go 1ed Edition Aaron Torres

https://ebookgate.com/product/go-cookbook-build-modular-readable-
and-testable-applications-in-go-1ed-edition-aaron-torres/

Go Play Golf Read It Watch It Do It GO SERIES Gavin


Newsham

https://ebookgate.com/product/go-play-golf-read-it-watch-it-do-
it-go-series-gavin-newsham/
Go Systems Programming

Master Linux and Unix system level programming with Go

Mihalis Tsoukalos

BIRMINGHAM - MUMBAI
Go Systems Programming
Copyright © 2017 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its
dealers and distributors will be held liable for any damages caused or alleged to be caused
directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: September 2017

Production reference: 1220917

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78712-564-3

www.packtpub.com
Credits

Author Copy Editor


Mihalis Tsoukalos Tom Jacob

Reviewer Proofreader
Chris "mac" McEniry Safis Editing

Acquisition Editor Indexer


Frank Pohlmann Tejal Daruwale Soni

Project Editor Graphics


Radhika Atitkar Kirk D'Penha

Content Development Editor Production Coordinator


Monika Sangwan Arvindkumar Gupta

Technical Editor
Anupam Tiwari
About the Author
Mihalis Tsoukalos is a Unix administrator, programmer, DBA, and mathematician, who
enjoys writing technical books and articles and learning new things. He has written more
than 250 technical articles for many magazines including Sys Admin, MacTech, Linux User
and Developer, USENIX ;login:, Linux Format, and Linux Journal. His research interests include
databases, operating systems, Statistics, and machine learning.

You can reach him at http://www.mtsoukalos.eu/ and @mactsouk.

Mihalis is also a photographer (http://www.highiso.net/).

He is also the technical editor for MongoDB in Action, Second Edition, published by Manning.

I would like to thank all the magazines that I have written articles for because they gave me
the opportunity to improve my technical writing skills and finally write my first book!
I would also like to thank Agisilaos Ziotopoulos for telling me during a Skype call that
after writing so many magazine articles, I should write a book!
Lastly, I would like to thank the people at Packt Publishing for helping me write this book,
including Frank Pohlmann, my technical reviewer; Chris McEniry, for his really good
comments; and especially my editor, Radhika Atitkar for answering all my questions and
encouraging me during the whole process.
For all potential writers everywhere: if you wish to become a writer, start writing!
About the Reviewer
Chris "mac" McEniry has been a practicing systems administrator and engineer for over
twenty years. He regularly presents, writes tools, and works on improving how we
maintain systems.
www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub.com. Did
you know that Packt offers eBook versions of every book published, with PDF and ePub
files available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entitled to a discount on the eBook copy.

Get in touch with us at [email protected] for more details. At www.PacktPub.com,


you can also read a collection of free technical articles, sign up for a range of free
newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt
books and video courses, as well as industry-leading tools to help you plan your personal
development and advance your career.

Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial
process. To help us improve, please leave us an honest review on this book's Amazon page
at https://www.amazon.com/dp/1787125645.

If you'd like to join our team of regular reviewers, you can email us at
[email protected]. We award our regular reviewers with free eBooks and
videos in exchange for their valuable feedback. Help us be relentless in improving our
products!
Table of Contents
Preface 1
Chapter 1: Getting Started with Go and Unix Systems Programming 9
The structure of the book 10
What is systems programming? 10
Learning systems programming 12
About Go 13
Getting ready for Go 14
Two useful Go tools 15
Advantages and disadvantages of Go 19
The various states of a Unix process 20
Exercises 22
Summary 22
Chapter 2: Writing Programs in Go 23
Compiling Go code 23
Checking the size of the executable file 26
Go environment variables 27
Using command-line arguments 29
Finding the sum of the command-line arguments 30
User input and output 33
Getting user input 33
Printing output 35
Go functions 35
Naming the return values of a Go function 36
Anonymous functions 36
Illustrating Go functions 36
The defer keyword 39
Using pointer variables in functions 42
Go data structures 43
Arrays 43
Slices 45
Maps 48
Converting an array into a map 50
Structures 51
Interfaces 53
Creating random numbers 56
Exercises 58
Summary 59
Chapter 3: Advanced Go Features 60
Error handling in Go 60
Functions can return error variables 61
About error logging 63
The addCLA.go program revisited 65
Pattern matching and regular expressions 66
Printing all the values from a given column of a line 68
Creating summaries 69
Finding the number of occurrences 71
Find and replace 73
Reflection 74
Calling C code from Go 76
Unsafe code 77
Comparing Go to other programming languages 78
Analysing software 80
Using the strace(1) command-line utility 80
The DTrace utility 83
Disabling System Integrity Protection on macOS 86
Unreachable code 86
Avoiding common Go mistakes 88
Exercises 88
Summary 89
Chapter 4: Go Packages, Algorithms, and Data Structures 90
About algorithms 91
The Big O notation 91
Sorting algorithms 92
The sort.Slice() function 92
Linked lists in Go 94
Trees in Go 98
Developing a hash table in Go 100
About Go packages 104
Using standard Go packages 104
Creating your own packages 105
Private variables and functions 107
The init() function 107
Using your own Go packages 108

[ ii ]
Using external Go packages 109
The go clean command 112
Garbage collection 112
Your environment 114
Go gets updated frequently! 116
Exercises 116
Summary 117
Chapter 5: Files and Directories 118
Useful Go packages 119
Command-line arguments revisited! 119
The flag package 119
Dealing with directories 122
About symbolic links 123
Implementing the pwd(1) command 124
Developing the which(1) utility in Go 126
Printing the permission bits of a file or directory 129
Dealing with files in Go 130
Deleting a file 130
Renaming and moving files 132
Developing find(1) in Go 134
Traversing a directory tree 135
Visiting directories only! 136
The first version of find(1) 137
Adding some command-line options 139
Excluding filenames from the find output 142
Excluding a file extension from the find output 144
Using regular expressions 145
Creating a copy of a directory structure 146
Exercises 151
Summary 151
Chapter 6: File Input and Output 152
About file input and output 153
Byte slices 153
About binary files 155
Useful I/O packages in Go 156
The io package 157
The bufio package 158
File I/O operations 160
Writing to files using fmt.Fprintf() 160

[ iii ]
About io.Writer and io.Reader 161
Finding out the third column of a line 163
Copying files in Go 166
There is more than one way to copy a file! 166
Copying text files 166
Using io.Copy 166
Reading a file all at once! 168
An even better file copy program 170
Benchmarking file copying operations 173
Developing wc(1) in Go 178
Counting words 178
The wc.go code! 178
Comparing the performance of wc.go and wc(1) 183
Reading a text file character by character 184
Doing some file editing! 186
Interprocess communication 188
Sparse files in Go 188
Reading and writing data records 191
File locking in Go 194
A simplified Go version of the dd utility 197
Exercises 200
Summary 200
Chapter 7: Working with System Files 201
Which files are considered system files? 202
Logging in Go 202
Putting data at the end of a file 202
Altering existing data 204
About log files 206
About logging 207
Logging facilities 207
Logging levels 207
The syslog Go package 208
Processing log files 210
File permissions revisited 214
Changing file permissions 216
Finding other kinds of information about files 218
More pattern matching examples 221
A simple pattern matching example 221
An advanced example of pattern matching 224
Renaming multiple files using regular expressions 227

[ iv ]
Searching files revisited 229
Finding the user ID of a user 229
Finding all the groups a user belongs to 231
Finding files that belong or do not belong to a given user 233
Finding files based on their permissions 236
Date and time operations 238
Playing with dates and times 238
Reformatting the times in a log file 240
Rotating log files 242
Creating good random passwords 245
Another Go update 247
Exercises 247
Summary 248
Chapter 8: Processes and Signals 249
About Unix processes and signals 250
Process management 250
About Unix signals 251
Unix signals in Go 252
The kill(1) command 252
A simple signal handler in Go 253
Handling three different signals! 255
Catching every signal that can be handled 257
Rotating log files revisited! 259
Improving file copying 262
Plotting data 266
Unix pipes in Go 273
Reading from standard input 274
Sending data to standard output 276
Implementing cat(1) in Go 277
The plotIP.go utility revisited 278
Unix sockets in Go 286
RPC in Go 287
Programming a Unix shell in Go 288
Yet another minor Go update 290
Exercises 290
Summary 291
Chapter 9: Goroutines – Basic Features 292
About goroutines 293

[v]
Concurrency and parallelism 293
The sync Go packages 294
A simple example 294
Creating multiple goroutines 295
Waiting for goroutines to finish their jobs 297
Creating a dynamic number of goroutines 299
About channels 301
Writing to a channel 301
Reading from a channel 303
Explaining h1s.go 304
Pipelines 305
A better version of wc.go 307
Calculating totals 310
Doing some benchmarking 314
Exercises 316
Summary 316
Chapter 10: Goroutines – Advanced Features 317
The Go scheduler 318
The sync Go package 318
The select keyword 318
Signal channels 321
Buffered channels 324
About timeouts 326
An alternative way to implement timeouts 328
Channels of channels 330
Nil channels 332
Shared memory 333
Using sync.Mutex 335
Using sync.RWMutex 339
The dWC.go utility revisited 342
Using a buffered channel 342
Using shared memory 345
More benchmarking 348
Detecting race conditions 349
About GOMAXPROCS 352
Exercises 354
Summary 354
Chapter 11: Writing Web Applications in Go 355
What is a web application? 356

[ vi ]
About the net/http Go package 356
Developing web clients 356
Fetching a single URL 356
Setting a timeout 358
Developing better web clients 360
A small web server 363
The http.ServeMux type 366
Using http.ServeMux 366
The html/template package 370
About JSON 375
Saving JSON data 376
Parsing JSON data 378
Using Marshal() and Unmarshal() 380
Using MongoDB 382
Basic MongoDB administration 382
Using the MongoDB Go driver 385
Creating a Go application that displays MongoDB data 388
Creating an application that displays MySQL data 392
A handy command-line utility 395
Exercises 399
Summary 400
Chapter 12: Network Programming 401
About network programming 402
About TCP/IP 402
About TCP 402
The TCP handshake! 403
About UDP and IP 403
About Wireshark and tshark 404
About the netcat utility 406
The net Go standard package 406
Unix sockets revisited 407
A Unix socket server 407
A Unix socket client 409
Performing DNS lookups 411
Using an IP address as input 412
Using a host name as input 413
Getting NS records for a domain 415
Developing a simple TCP server 416
Developing a simple TCP client 419

[ vii ]
Using other functions for the TCP server 421
Using alternative functions for the TCP client 423
Developing a simple UDP server 424
Developing a simple UDP client 426
A concurrent TCP server 428
Remote procedure call (RPC) 430
An RPC server 431
An RPC client 434
Exercises 436
Summary 437
Index 438

[ viii ]
Preface
Go Systems Programming is a book that will help you develop systems software using Go,
which is a systems programming language that started as an internal Google project before
becoming popular. What makes Go really popular is that it keeps the developer happy by
being easy to write, easy to read, easy to understand, and by having a compiler that is there
to help you. This book does not cover every possible aspect and feature of the Go
programming language—only the ones that are related to systems programming. Should
you wish to learn more about the Go programming language, you should wait from my
next book, Mastering Go, which will be ready in 2018!

The book you are about to read is an honest book in the sense that it will present working
Go code without overlooking its potential faults, its restrictions, and its logical gaffes, which
will allow you to improve it on your own and create a better version of it in the future.
What you will not be able to improve is the fundamental information that will be presented,
which is the basis of the way Unix systems work. I will consider the book to be successful if
it helps you understand what systems programming is about, why it is important, and how
you can start developing systems software in Go. I will be equally happy if Go becomes
your favorite programming language!

What this book covers


Chapter 1, Getting started with Go and Unix Systems Programming, starts by defining what
systems programming is before talking about the advantages and the disadvantages of Go,
the features of Go version 1.8, two handy Go tools named gofmt and godoc, as well as the
various states of Unix processes.

Chapter 2, Writing Programs in Go, helps you learn how to compile Go code and how to use
the environment variables that Go supports, and understand how Go reads the command
line arguments of a program. Then, we will talk about getting user input and output, which
are fundamental tasks, show you how to define functions in Go, where the defer keyword
is mentioned for the first time in this book and continue by discussing the data structures
that Go offers using handy code examples. In the remaining sections of the chapter, we will
discuss Go interfaces and random number generation. I am sure that you are going to enjoy
this chapter!
Preface

Chapter 3, Advanced Go Features, goes deeper and starts talking about some advanced Go
features, including error handling, which is critical when developing systems software and
error logging. Then it introduces you to pattern matching and regular expressions, Go
Reflection, and talks about unsafe code. After that, it compares Go to other programming
languages and presents two utilities, named dtrace(1) and strace(1), that allow you to
see what happens behind the scenes when you execute a program. Lastly, it talks about how
you can use the go tool to detect unreachable code and how to avoid some common Go
mistakes.

Chapter 4, Go Packages, Algorithms, and Data Structures, talks about algorithms and sorting
in Go and about the sort.Slice() function, which requires Go version 1.8 or newer. Then
it shows Go implementations of a linked list, a binary tree and a hash table. After that, it
discusses Go packages and teaches you how to create and use your own Go packages. The
last part of the chapter discusses Garbage collection in Go.

Chapter 5, Files and Directories, is the first chapter of this book that deals with a systems
programming topic, which is the handling of files, symbolic links, and directories. In this
chapter, you will find Go implementations of the core functionality of Unix tools such as
which(1), pwd(1), and find(1), but first you will learn how to use the flag package in
order to parse the command-line arguments and options of a Go program. Additionally,
you will learn how to delete, rename, and move files as well as how to traverse directory
structures the Go way. The last part of this chapter implements a utility that creates a copy
of all the directories of a directory structure!

Chapter 6, File Input and Output, shows you how to read the contents of a file, how to
change them, and how to write your own data to files! In this chapter, you will learn about
the io package, the io.Writer and io.Reader interfaces, and the bufio package that is
used for buffered input and output. You will also create Go versions of the cp(1), wc(1),
and dd(1) utilities. Lastly, you will learn about sparse files, how to create sparse files in Go,
how to read and write records from files, and how to lock files in Go.

Chapter 7, Working with System Files, teaches you how to deal with Unix system files, which
includes writing data to Unix log files, appending data to existing files, and altering the
data of text files. In this chapter, you will also learn about the log and log/syslog standard
Go packages, about Unix file permissions, and take your pattern matching and regular
expressions knowledge even further using practical examples. You will also learn about
finding the user ID of a user as well as the Unix groups a user belongs to. Lastly, you will
discover how to work with dates and times in Go using the time package and how to create
and rotate log files on your own.

[2]
Preface

Chapter 8, Processes and Signals, begins by discussing the handling of Unix signals in Go
with the help of the os/signal package by presenting three Go programs. Then it shows a
Go program that can rotate its log files using signals and signal handling and another Go
program that uses signals to present the progress of a file copy operation. This chapter will
also teach you how to plot data in Go and how to implement Unix pipes in Go. Then it will
implement the cat(1) utility in Go before briefly presenting the Go code of a Unix socket
client. The last section of the chapter quickly discusses how you can program a Unix shell in
Go.

Chapter 9, Goroutines – Basic Features, discusses a very important Go topic, which is


goroutines, by talking about how you can create goroutines and how you can synchronize
them and wait for them to finish before ending a program. Then it talks about channels and
pipelines, which help goroutines communicate and exchange data in a safe way. The last
part of the chapter presents a version of the wc(1) utility that is implemented using
goroutines. However, as goroutines is a big subject, the next chapter will continue talking
about them.

Chapter 10, Goroutines – Advanced Features, talks about more advanced topics related to
goroutines and channels, including buffered channels, signal channels, nil channels,
channels of channels, timeouts, and the select keyword. Then it discusses issues related to
shared memory and mutexes before presenting two more Go versions of the wc(1) utility
that use channels and shared memory. Lastly, this chapter will talk about race conditions
and the GOMAXPROCS environment variable.

Chapter 11, Writing Web Applications in Go, talks about developing web applications and
web servers and clients in Go. Additionally, it talks about communicating with MongoDB
and MySQL databases using Go code. Then, it illustrates how to use the html/template
package, which is part of the Go standard library and allows you to generate HTML output
using Go HTML template files. Lastly, it talks about reading and writing JSON data before
presenting a utility that reads a number of web pages and returns the number of times a
given keyword was found in those web pages.

Chapter 12, Network Programming, discusses topics related to TCP/IP and its protocols using
the net Go standard package. It shows you how to create TCP and UDP clients and servers,
how to perform various types of DNS lookups, and how to use Wireshark to inspect
network traffic. Additionally, it talks about developing RPC clients and servers in Go as
well as developing a Unix socket server and a Unix socket client.

As you will see, at the end of each chapter there are some exercises for you to do in order to
gain more information about important Go packages and write your own Go programs.
Please, try to do all the exercises of this book.

[3]
Preface

What you need for this book


This book requires a computer running a Unix variant with a relatively recent Go version,
which includes any machine running Mac OS X, macOS, or Linux.

Apple used to call its operating system as Mac OS X followed by the version number;
however, after Mac OS X 10.11 (El Capitan), Apple changed that, and Mac OS X 10.12 is
now called macOS 10.12 (Sierra) – in this book, the terms Mac OS X and macOS are used
interchangeably. Additionally, there is a big chance that by the time you read this book, the
latest version of macOS will be macOS 10.13 (High Sierra). You can learn more about the
various versions of macOS by visiting https://en.wikipedia.org/wiki/MacOS.

All of the Go code in this book has been tested with Go 1.8.x running on a iMac using
macOS 10.12 Sierra and with Go version 1.3.3 running on a Debian Linux machine. Most of
the code can run on both Go versions without any code changes. However, when newer Go
features are used, the code will fail to compile with Go 1.3.3—the book states the Go
programs that will not compile with Go version 1.3.3 or require Go version 1.8 or newer.

Please note that at the time of writing this text, the latest Go version is 1.9. Given the way
Go works, you will be able to compile all the Go code of this book in newer Go versions
without any changes.

Who this book is for


This book is for Unix users, power Unix users, Unix system administrators, and Unix
system developers that use Go on one or more Unix variants and want to start developing
systems software using the Go programming language.

Although this book might not be the best choice for people that do not feel comfortable with
the Unix operating system or for people who have no previous programming experience,
amateur programmers will find lots of practical information about Unix that might inspire
them to start developing their own system utilities.

Conventions
In this book, you will find a number of text styles that distinguish between different kinds
of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "This is
because the main() function is where the program execution begins."

[4]
Preface

A block of code is set as follows:


package main

import "fmt"
import "os"

func main() {
arguments := os.Args
for i := 0; i < len(arguments); i++ {
fmt.Println(arguments[i])
}
}

When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
package main

import "fmt"
import "os"

func main() {
arguments := os.Args
for i := 0; i < len(arguments); i++ {
fmt.Println(arguments[i])
}
}

Any command-line input or output is written as follows:


$ go run hw.go
Hello World!

New terms and important words are shown in bold.

Warnings or important notes appear like this.

Tips and tricks appear like this.

[5]
Preface

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this
book-what you liked or disliked. Reader feedback is important for us as it helps us develop
titles that you will really get the most out of. To send us general feedback, simply email
[email protected], and mention the book's title in the subject of your message. If
there is a topic that you have expertise in and you are interested in either writing or
contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you
to get the most from your purchase.

Downloading the example code


You can download the example code files for this book from your account at
http://www.packtpub.com. If you purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:

1. Log in or register to our website using your email address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box.
5. Select the book for which you're looking to download the code files.
6. Choose from the drop-down menu where you purchased this book from.
7. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:

WinRAR / 7-Zip for Windows


Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux

[6]
Preface

The code bundle for the book is also hosted on GitHub at


https://github.com/PacktPublishing/Go-Systems-Programming. We also have other code
bundles from our rich catalog of books and videos available at
https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book


We also provide you with a PDF file that has color images of the screenshots/diagrams used
in this book. The color images will help you better understand the changes in the output.
You can download this file from
https://www.packtpub.com/sites/default/files/downloads/GoSystemsProgramming_Col
orImages.pdf.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-
we would be grateful if you could report this to us. By doing so, you can save other readers
from frustration and help us improve subsequent versions of this book. If you find any
errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting
your book, clicking on the Errata Submission Form link, and entering the details of your
errata. Once your errata are verified, your submission will be accepted and the errata will
be uploaded to our website or added to any list of existing errata under the Errata section of
that title. To view the previously submitted errata, go to
https://www.packtpub.com/books/content/support and enter the name of the book in the
search field. The required information will appear under the Errata section.

Piracy
Piracy of copyrighted material on the internet is an ongoing problem across all media. At
Packt, we take the protection of our copyright and licenses very seriously. If you come
across any illegal copies of our works in any form on the internet, please provide us with
the location address or website name immediately so that we can pursue a remedy. Please
contact us at [email protected] with a link to the suspected pirated material. We
appreciate your help in protecting our authors and our ability to bring you valuable
content.

[7]
Preface

Questions
If you have a problem with any aspect of this book, you can contact us at
[email protected], and we will do our best to address the problem.

[8]
Getting Started with Go and
1
Unix Systems Programming
An operating system is the kind of software that allows you to communicate with the
hardware, which means that you cannot use your hardware without an operating system.
Unix is an operating system with many variants that have many things in common
including their programming interface.

The Unix operating system was mainly programmed in C and not entirely in the assembly
language, which makes it portable to other computer architectures without having to
rewrite everything from scratch. It is important to understand that even if you are
developing a Go program on a Unix machine, at the end of the day, your code will be
translated to C functions and system calls because this is the only way to directly
communicate with the Unix kernel. The main benefits you get from writing Go code instead
of C code are smaller programs with less silly bugs. You will learn more about this in
Chapter 3, Advanced Go Features.

As this book will use Go, you will need to have a version of Go installed on your Unix
machine. The good news is that there is a port of the Go programming language for almost
all modern Unix systems including macOS, Linux, and FreeBSD. There is also a Windows
port of Go, but this book will not deal with Microsoft Windows.

Although there is a good chance that your Unix variant has a package for Go, you can also
get Go from https://golang.org/dl/.
Getting Started with Go and Unix Systems Programming

In this chapter, you will learn the following topics:

Systems programming
The advantages and disadvantages of Go
The states of a Unix process
Two Go tools: gofmt and godoc
The features of the latest Go version (1.8)

The structure of the book


This book has three parts. The first part, which includes this chapter, is about Go and the Go
features that can be handy when developing systems software—this does not mean that you
should use all of them when developing your programs. The second part is all about
programming with files, directories, and processes, which is the most common type of
systems software. The third part explores goroutines, web applications, and network
programming in Go, which is the most advanced type of systems software. The good thing
is that you do not need to read the third part of the book right away.

What is systems programming?


Systems programming is a special area of programming on Unix machines. Note that
systems programming is not limited to Unix machines—it is just that this book deals with
the Unix operating system only. Most commands that have to do with system
administration tasks, such as disk formatting, network interface configuration, module
loading, and kernel performance tracking, are implemented using the techniques of systems
programming. Additionally, the /etc directory, which can be found on all Unix systems,
contains plain text files that deal with the configuration of a Unix machine and its services
and are also manipulated using systems software.

You can group the various areas of systems software and related system calls in the
following sets:

File I/O: This area deals with file reading and writing operations, which is the
most important task of an operating system. File input and output must be fast
and efficient, and above all, reliable.
Advanced file I/O: Apart from the basic input and output system calls, there are
also more advanced ways to read or write to a file including asynchronous I/O
and non-blocking I/O.

[ 10 ]
Getting Started with Go and Unix Systems Programming

System files and configuration: This group of system software includes


functions that allow you to handle system files, such as /etc/passwd, and get
system specific information, such as system time and DNS configuration.
Files and directories: This cluster includes functions and system calls that allow
the programmer to create and delete directories and get information such as the
owner and the permissions of a file or a directory.
Process control: This group of software allows you to create and interact with
Unix processes.
Threads: When a process has multiple threads, it can perform multiple tasks.
However, threads must be created, terminated, and synchronized, which is the
purpose of this collection of functions and system calls.
Server processes: This set includes techniques that allow you to develop server
processes, which are processes that get executed in the background without the
need for an active terminal. Go is not that good at writing server processes in the
traditional Unix way—but let me explain this a little more. Unix servers such as
Apache use fork(2) to create one or more child processes (this process is called
forking and refers to cloning the parent process into a child process) and
continue executing the same executable from the same point, and most
importantly, sharing memory. Although Go does not offer an equivalent to the
fork(2) function, this is not an issue because you can use goroutines to cover
most of the uses of fork(2).
Interprocess communication: This set of functions allows processes that run on
the same Unix machine to communicate with each other using features such as
pipes, FIFOs, message queues, semaphores, and shared memory.
Signal processing: Signals offer processes a way of handling asynchronous
events, which can be very handy. Almost all server processes have extra code that
allows them to handle Unix signals using the system calls of this group.
Network programming: This is the art of developing applications that work over
computer networks with the help of TCP/IP and is not systems programming per
se. However, most TCP/IP servers and clients are dealing with system resources,
users, files, and directories. So, most of the time, you cannot create network
applications without doing some kind of systems programming.

The challenging thing with systems programming is that you cannot afford to have an
incomplete program; you can either have a fully working, secure program that can be used
on a production system or nothing at all. This mainly happens because you cannot trust end
users and hackers. The key difficulty in systems programming is the fact that an erroneous
system call can make your Unix machine misbehave or, even worse, crash!

[ 11 ]
Getting Started with Go and Unix Systems Programming

Most security issues on Unix systems usually come from wrongly implemented systems
software because bugs in systems software can compromise the security of an entire system.
The worst part is that this can happen many years after using a certain piece of software.

When writing systems software, you should take good care of both error
messages and warnings because they are the friends that help you
understand what is going on and why your program did not behave as
expected. Putting it simply, there is a big difference between the File not
found and Not enough permissions to read file error messages.

Back when Unix was first introduced, the only way to write systems software was using C;
nowadays, you can program systems software using programming languages including Go,
which will be the subject of this book.

You should understand that the two main benefits you get from using a programming
language other than C for developing systems software are as follows:

Using a modern programming language along with its tools


Simplicity, as you usually have to write, debug, and maintain less code

Apart from Go, other good candidates for developing system tools are Python, Perl, Rust,
and Ruby.

Learning systems programming


The only way you can learn systems programming is by developing your own utilities
using this book as a reference and a tutorial. At first, you will make a large amount of
ridiculous mistakes, but as you get better, you will make a smaller amount of much more
clever and hard to debug mistakes! However, it is fine to try new things when learning. In
fact, it is necessary to try new things and fail because this means that you are really learning
something new. Just make sure that you do not use a production web server for learning
systems programming.

If you have difficulties finding out what to develop, you can start by creating your own
versions of some of the existing Unix command line utilities such as ls(1), mkdir(1),
ln(1), wc(1), and which(1). You do not have to create a fully featured version of each
one of them with support for all command-line options; what is important is to develop a
stable and secure version that implements the main functionality and works without
problems.

[ 12 ]
Getting Started with Go and Unix Systems Programming

The best book that can teach you Unix systems programming in C is
Advanced Unix Programming in the Unix Environment by W. Richard Stevens.
Its third edition is available now, but all its editions are useful and contain
a plethora of valuable details.

About Go
Go is a modern generic purpose open source programming language that was officially
announced at the end of 2009. It began as an internal Google project and has been inspired
by many other programming languages including C, Pascal, Alef, and Oberon. Its spiritual
fathers are Robert Griesemer, Ken Thomson, and Rob Pike, who designed Go as a language for
professional programmers who want to build reliable and robust software. Apart from its
syntax and standard functions, Go comes with a pretty rich standard library.

At the time of writing this book, the latest stable Go version is 1.8, which includes some
handy new features including the following—feel free to skip this if you have not used Go
before:

New conversion rules exist that allow you to easily convert between types that
are almost equal provided that some criteria are met. You can fix the import
paths of the golang.org/x/net/name form to just the name of the Go source
file using the go tool command without having to open the source files
yourselves.
The operation of the tool is stricter in some cases and looser in cases that used to
generate false positives.
There is now a default value for GOPATH Environment Variables when
GOPATH is undefined. For Unix systems, the default value is $HOME/go.
There are various improvements to the Go runtime that speed up Go.
There is a sort.slice() function that allows you to sort a slice by providing a
comparator callback instead of implementing sort.Interface.
There is now a Shutdown method to http.Server.
There exist various small changes to the database/sql package that give the
developer more control over queries.
You can create bugs using the go bug command.

[ 13 ]
Getting Started with Go and Unix Systems Programming

Getting ready for Go


You can easily find your version of Go using this command:
$ go version
go version go1.7.5 darwin/amd64

The previous output is from a macOS machine hence the darwin string. A Linux machine
would give the following kind of output:
$ go version
go version go1.3.3 linux/amd64

You will learn more about go tool, which you will use all the time, in the next chapters.

As I can imagine, you must be impatient to see some Go code; so here is the Go version of
the famous Hello World program:
package main

import "fmt"

// This is a demonstrative comment!


func main() {
fmt.Println("Hello World!")
}

If you are familiar with C or C++, you will find Go code pretty easy to understand. Each file
that contains Go code begins with a package declaration followed by the needed import
declarations. The package declaration shows the package that this file belongs to. Note that
semicolons are not required for successfully terminating a Go statement unless you want to
put two or more Go statements in the same line.

In Chapter 2, Writing Programs in Go, you will find out how to compile and execute Go
code. For now, it is enough to remember that Go source files are stored using the .go file
extension—your task is to choose a descriptive filename.

When searching for Go-related information, use Golang or golang as the


keyword for the Go programming language because the word Go can be
found almost everywhere in the English language and it will not help your
search!

[ 14 ]
Getting Started with Go and Unix Systems Programming

Two useful Go tools


The Go distribution comes with a plethora of tools that can make your life as a programmer
easier. The two most useful of them are gofmt and godoc.

Note that go tool itself can also invoke various tools—you can see a list
of them by executing go tool.

The gofmt utility formats Go programs in a given way, which is really important when
different people are going to work with the same code for a big project. You can find more
information about gofmt at https://golang.org/cmd/gofmt/.

The following is a poorly formatted version of the hw.go program that is hard to read and
understand:
$ cat unglyHW.go
package main
import
"fmt"
// This is a demonstrative comment!
func main() {
fmt.Println("Hello World!")
}

Processing the previous code, which is saved as unglyHW.go with gofmt, generates the
following easy to read and comprehend output:
$ gofmt unglyHW.go
package main
import "fmt"
// This is a demonstrative comment!
func main() {
fmt.Println("Hello World!")
}

Remembering that the gofmt utility does not automatically save the generated output is
important, which means that you should either use the -w option followed by a valid
filename or redirect the output of gofmt to a new file.

The godoc utility allows you to see the documentation of existing Go packages and
functions. You can find more information about godoc at
http://godoc.org/golang.org/x/tools/cmd/godoc.

[ 15 ]
Getting Started with Go and Unix Systems Programming

You are going to use godoc a lot as it is a great tool for learning the details
of Go functions.

The following screenshot shows the output of the godoc command generated on a Terminal
when asked for information about the Println() function of the fmt package:

The output of the godoc command

[ 16 ]
Getting Started with Go and Unix Systems Programming

Another handy feature of godoc is that it can start its own web server and allow you to see
its documentation using a web browser:
$ godoc -http=:8080

The following screenshot shows the kind of output you get on a web browser after visiting
http://localhost:8080/pkg/ while the previous command is running. You can use any
port number you want, provided that it is not already in use:

Using the godoc utility from your web browser

[ 17 ]
Getting Started with Go and Unix Systems Programming

The most important tool for a programmer is the editor they use for writing the source
code. When I am on a Mac, I typically use the TextMate editor, but when I am on a different
Unix machine, I prefer vi. Choosing an editor is not an easy task because you are going to
spend a lot of time with it. However, any text editor will do the job as long as it does not put
any control characters inside the source code files. The following screenshot shows the
TextMate editor in action:

The TextMate editor showing the look of a some Go code

[ 18 ]
Getting Started with Go and Unix Systems Programming

Advantages and disadvantages of Go


Go is not perfect but it has some very interesting features. The list of the Go strong features
includes the following:

Go code is easy to read and easy to understand.


Go wants happy developers because a happy developer writes better code!
The Go compiler prints practical warning and error messages that help you solve
the actual problem. Putting it simply, the Go compiler is there to help you, not to
make your life difficult!
Go code is portable.
Go is a modern programming language.
Go has support for procedural, concurrent, and distributed programming.
Go supports Garbage Collection (GC) so you do not have to deal with memory
allocation and deallocation. However, GC might slow down your programs a
little.
Go does not have a preprocessor and does high-speed compilation.
Consequently, Go can be used as a scripting language.
Go can build web applications. Building a web application in C is simply not very
efficient unless you use a nonstandard external library. Additionally, Go provides
programmers with a simple web server for testing purposes.
The standard Go library offers many packages that simplify the work of the
programmer. Additionally, the methods found in the standard Go library are
tested and debugged in advance, which means that most of the time they contain
no bugs.
Go uses static linking by default, which means that the produced binary files can
be easily transferred to other machines with the same OS. Consequently, the
developer does not need to worry about libraries, dependencies, and different
library versions.
You will not need a GUI for developing, debugging, and testing Go applications
as Go can be used from the command line.
Go supports Unicode. This means that you do not need any extra code to print
characters from multiple human languages.
Go keeps concepts orthogonal because a few orthogonal features work better
than many overlapping ones.

[ 19 ]
Getting Started with Go and Unix Systems Programming

The list of Go disadvantages includes the following:

Well, Go is not C, which means that you or your team should learn a new
programming language to develop systems software.
Go does not have direct support for object-oriented programming, which can be a
problem for programmers that are used to writing code in an object-oriented
manner. Nevertheless, you can use composition in Go to mimic inheritance.
Back when Unix was first introduced, C was the only programming language for
writing systems software. Nowadays, you can also use Rust, C++, and Swift for
writing systems software, which means that not everybody will be using Go.
C is still faster than any other programming language for systems programming
mainly because Unix is written in C.

Despite the advantages or the disadvantages of a programming language,


you have the final word on whether you like it or not. The important thing
is that you choose a programming language that you like and can do the
job you want! Personally, I do not like C++ despite the fact that it is a very
capable programming language and I have written an FTP client in C++!
Additionally, I never liked Java. There is no right or wrong thing in
personal tastes so do not feel guilty about your choices.

The various states of a Unix process


Strictly speaking, a process is an execution environment that contains instructions, user-
data and system-data parts, and other kinds of resources that are obtained during runtime.
A program is a file that contains instructions and data, which are used for initializing the
instruction and user-data parts of a process.

Back when the Unix operating system was first introduced, computers had single CPUs
without multiple cores and a small amount of RAM. However, Unix was a multiuser and
multitasking operating system. In order to actually be a multiuser and do multitasking, it
had to be able to run each individual process sporadically, which means that a process
should have multiple states. The following figure shows the possible states of a process as
well as the right path to go from one state to another:

[ 20 ]
Getting Started with Go and Unix Systems Programming

The states of a Unix process

There are three categories of processes: user processes, Kernel processes, and Daemon
processes:

User processes run in user space and usually have no special access rights
Kernel processes are being executed in kernel space only and can fully access all
kernel data structures
Daemon processes are programs that can be found in the user space and run in
the background without the need for a Terminal

Realizing that you cannot control the state of a process is really important, as this is the job
of the scheduler of the operating system that runs in the kernel. Putting it simply, you
cannot tell when the state of a process is going to change or when the process is going to go
into the running state, so your code cannot count on any such assumptions!

The C way for creating new processes involves the calling of the fork()
system call. The return value of fork() allows the programmer to
differentiate between the parent and child processes. However, Go does
not support a similar functionality.

[ 21 ]
Getting Started with Go and Unix Systems Programming

Exercises
1. Visit the Go website: https://golang.org/.
2. Install Go on your system and find out its version.
3. Type the code of the Hello World program on your own and save it to a file.
4. If you are on a Mac, download TextMate from http://macromates.com/.
5. If you are on a Mac, download the TextWrangler editor from
http://www.barebones.com/products/TextWrangler/ and try it.
6. Try to learn vi or Emacs on your own if you are not already familiar with another
Unix text editor.
7. Look at any Go code you can find and try to make small changes to it.

Summary
In this chapter, you learned how to get Go on your computer, the features of the latest Go
version, the advantages and disadvantages of Go, and the gofmt and godoc Go tools, as
well as some important things about the Unix operating system.

The next chapter will not only tell you how to compile your Go code but it will also discuss
other important Go topics such as reading and using command-line arguments,
environment variables, writing functions, data structures, interfaces, getting user input, and
printing output.

[ 22 ]
Writing Programs in Go
2
This chapter will talk about many essential, interesting, and handy Go topics that will help
you be more productive. I think it would be a good idea to start this chapter by compiling
and running the Go code of the hw.go program from the previous chapter. Then, you will
learn how to deal with the environment variables that can be used by Go, how to process
the command-line arguments of a Go program, and how to print the output on the screen
and get input from the user. Finally, you will see how to define functions in Go, learn about
the extremely important defer keyword, look at the data structures that come with Go, and
learn what Go interfaces are before checking out code that generates random numbers.

Therefore, in this chapter, you will become familiar with many Go concepts, including the
following:

Compiling your Go programs


Go environment variables
Using the command-line arguments given to a Go program
Getting user input and printing the output on your screen
Go functions and the defer keyword
Go data structures and interfaces
Creating random numbers

Compiling Go code
Go does not care about the name of the source file of an autonomous program as long as the
package name is main and there is a main() function in it. This is because the main()
function is where the program execution begins. This also means that you cannot have
multiple main() functions in the files of a single project.
Writing Programs in Go

There exist two ways to run a Go program:

The first one, go run, just executes the Go code without generating any new
files, only some temporary ones that are deleted afterward
The second way, go build, compiles the code, generates an executable file, and
waits for you to run the executable file

This book is written on an Apple Mac OS Sierra system using the Homebrew (https:/​/
brew.​sh/​) version of Go. However, you should have no difficulties compiling and running
the presented Go code on most Linux and FreeBSD systems, provided that you have a
relatively recent version of Go.

So, the first way is as follows:


$ go run hw.go
Hello World!

The aforementioned way allows Go to be used as a scripting language. The following is the
second way:
$ go build hw.go
$ file hw
hw: Mach-O 64-bit executable x86_64

The generated executable file is named after the name of the Go source file, which is much
better than a.out, which is the default filename of the executable files generated by the C
compiler.

If there is an error in your code, such as a misspelled Go package name when calling a Go
function, you will get the following kind of error message:
$ go run hw.go
# command-line-arguments
./hw.go:3: imported and not used: "fmt"
./hw.go:7: undefined: mt in mt.Println

If you accidentally misspell the main() function, you will get the following error message
because the execution of an autonomous Go program begins from the main() function:
$ go run hw.go
# command-line-arguments
runtime.main_main f: relocation target main.main not defined
runtime.main_main f: undefined: "main.main"

[ 24 ]
Writing Programs in Go

Lastly, I want to show you an error message that will give you a good idea about a
formatting rule of Go:
$ cat hw.gocat
package main
import "fmt"
func main()
{
fmt.Println("Hello World!")
}
$ go run hw.go
# command-line-arguments
./hw.go:6: syntax error: unexpected semicolon or newline before {

The previous error message shows us that Go prefers putting curly braces in a certain way,
which is not the case with most programming languages such as Perl, C, and C++. This
might look frustrating at first, but it saves you from one extra line of code and makes your
programs more readable. Note that the preceding code uses the Allman formatting style,
which Go does not accept.

The official explanation for this error is that Go requires the use of semicolons as statement
terminators in many contexts, and the compiler automatically inserts the required
semicolons when it thinks they are necessary, which in this case is at the end of a non-blank
line. Therefore, putting the opening brace ({) on its own line will make the Go compiler to
put a semicolon at the end of the previous line, which produces the error message.

If you think that the gofmt tool can save you from similar errors, you will be disappointed:
$ gofmt hw.go
hw.go:6:1: expected declaration, found '{'

The Go compiler has another rule, as you can see in the following output:
$ go run afile.go
# command-line-arguments
./afile.go:4: imported and not used: "net"

This means that you should not import packages without actually using them in your
programs. Although this could have been a harmless warning message, your Go program
will not get compiled. Bear in mind that similar warnings and error messages are a good
indication that you are missing something, and you should try to correct them. You will
create a higher quality of code if you treat warnings and errors the same.

[ 25 ]
Writing Programs in Go

Checking the size of the executable file


So, after successfully compiling hw.go, you might want to check the size of the generated
executable file:
$ ls -l hw
-rwxr-xr-x 1 mtsouk staff 1628192 Feb 9 22:29 hw
$ file hw
hw: Mach-O 64-bit executable x86_64

Compiling the same Go program on a Linux machine will create the following file:
$ go versiongo
go version go1.3.3 linux/amd64
$ go build hw.go
$ ls -l hw
-rwxr-xr-x 1 mtsouk mtsouk 1823712 Feb 18 17:35 hw
$ file hw
hw: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked,
not stripped

To get a better sense of how big the Go executable is, consider that the
executable for the same program written in C is about 8432 bytes!

So, you might ask why such a huge executable file for such a small program? The main
reason is that Go executable files are statically build, which means that they require no
external libraries to run. The use of the strip(1) command can make the generated
executable files a little smaller, but do not expect miracles:
$ strip hw
$ ls -l hw
-rwxr-xr-x 1 mtsouk staff 1540096 Feb 18 17:41 hw

[ 26 ]
Writing Programs in Go

The previous process has nothing to do with Go itself because strip(1) is a Unix
command that removes or modifies the symbol table of files and therefore reduces their
size. Go can perform the work of the strip(1) command on its own and create smaller
executable files, but this method does not always work:
$ ls -l hw
-rwxr-xr-x 1 mtsouk mtsouk 1823712 Feb 18 17:35 hw
$ CGO_ENABLED=0 go build -ldflags "-s" -a hw.go
$ ls -l hw
-rwxr-xr-x 1 mtsouk mtsouk 1328032 Feb 18 17:44 hw
$ file hw
hw: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked,
stripped

The preceding output is from a Linux machine; when the same compilation command is
used on a macOS machine, it will make no difference to the size of the executable file.

Go environment variables
The go tool can use many Unix shell environment variables dedicated to Go, including
GOROOT, GOHOME, GOBIN, and GOPATH. The most important Go environment variable is
GOPATH, which specifies the location of your workspace. Usually, this is the only
environment variable that you will need to define when developing Go code; it is to do with
the way the files of a project will be organized. This means that each project will be
organized into three main directories, named src, pkg, and bin. However, many people,
including me, prefer not to use GOPATH and manually organize their project files.

So, if you are a big fan of shell variables, you can put all these kinds of definitions in either
.bashrc or .profile, which means that these environment variables will be active every
time you log in to your Unix machine. If you are not using the Bash shell, which is the
default Linux and macOS shell, then you might need to use another start up file. Check out
the documentation of your favorite Unix shell to find out which file to use.

[ 27 ]
Writing Programs in Go

The upcoming screenshot shows part of the output of the following command, which
displays all the environment variables used by Go:
$ go help environment

The output of the "go help environment" command

[ 28 ]
Writing Programs in Go

You can find additional information about a particular environment variable by executing
the next command and replacing NAME with the environment variable that interests you:
$ go env NAME

All these environment variables have nothing to do with the actual Go code or the
execution of the program, but they might affect the development environment; therefore, if
you happen to see any strange behavior while trying to compile a Go program, check the
environment variables you are using.

Using command-line arguments


Command-line arguments allow your programs to get input, such as the names of the files
you want to process, without having to write a different version of the program. Hence, you
cannot create any useful systems software if you're unable to process the command-line
arguments passed to it.

So here is a naïve Go program, named cla.go, that prints all its command-line arguments,
including the name of the executable file:
package main

import "fmt"
import "os"

func main() {
arguments := os.Args
for i := 0; i < len(arguments); i++ {
fmt.Println(arguments[i])
}
}

As you can see, Go needs an extra package named os in order to read the command-line
arguments of a program that are stored in the os.Args array. In case you do not like
having multiple import statements, you can rewrite the two import statements as follows,
which I find much easier to read:
import (
"fmt"
"os"
)

[ 29 ]
Another Random Scribd Document
with Unrelated Content
English liberties, had it not been for the fact that he was married to
the daughter of James II., and of this marriage Lord Macaulay truly
says: “His choice had been determined chiefly by political
considerations, nor did it seem likely that any strong affection would
grow up between a handsome girl of sixteen, well-disposed, indeed,
and naturally intelligent, but ignorant and simple, and a bridegroom
who, though he had not completed his twenty-eighth year, was in
constitution older than her father; whose manner was chilling, and
whose head was constantly occupied by public business or by field
sports.”
His marriage was, in short, “a marriage of convenience,” and yet,
in defiance of all the rules that are supposed to govern the most
intimate of all human relationships, it was one of the best and, in the
end, most devoted unions that history has to record. It is hardly
possible to doubt that William of Orange married Mary Stuart
because he saw with that keenly penetrating foresight of his that
such a union would strengthen him in his life-long combat with the
arch-enemy of his faith, his family, and his nation; and this enemy
was that same Louis of France who had made Charles II. his
pensioner, and was soon to make James II. his dependent.
To quote Lord Macaulay again: “He saved England, it is true, but
he never loved her, and he never obtained her love.... Whatever
patriotic feeling he had was for Holland ... yet even his affection for
the land of his birth was subordinate to another feeling which early
became supreme in his soul, which mixed itself with all his passions
and compelled him to marvellous enterprises, which supported him
when sinking under mortification, pain, sickness, and sorrow ... and
continued to animate him even while the prayer for the departing
was read at his bedside.”
It was this hatred of France and her king which nerved him to do
for the liberties of Europe and Great Britain what Francis Drake had
done for England against Philip of Spain, and in the doing of this he
won the conspicuous glory of forcing the paymaster of the two
English sovereigns whom he succeeded, to make peace with him on
equal terms; and this, too, although he lost more battles than he
won, and had to surrender more strong cities than he took.
It is comparatively easy for a conqueror to take triumph out of
victory, but it is a higher quality which patiently endures defeat and
confronts disaster, and by sheer genius wins triumph in the end. This
is what William of Orange did, and it is from this fact that he derives
his title to be ranked among the Makers of that Empire to whose
throne he came as an alien, and whose honour he restored and
upheld, as one might say, in spite of herself.
So far as England is concerned, the male line of Stuart came in
with a fool and went out with a coward. One does not even care to
imagine what would have happened if James II. had remained on
the throne; or if William of Orange, with his hereditary and deep-
rooted hatred of Louis XIV. and his policy, had not come to take his
most miserably-vacated place in the nick of time.
The sentimentality which makes such a fuss about loyalty to
persons as distinguished from loyalty to country, and the lawyer-
quibbles which occupied men’s minds in the dispute as to whether
James II. was King de facto or de jure, or both, of the country from
which he had run away like an absconding debtor, may be dismissed,
just as Harold the Saxon’s claims had been some six hundred years
before. It is merely a question of the Fit and the Unfit, and James
was Unfit.
James Stuart deserted his post as ruler of these realms because
he found himself assailed by difficulties which the most ordinary
ability ought to have overcome. William assumed the same position
in the face of difficulties which only the highest qualities of kingcraft
and statesmanship could have enabled him to successfully grapple
with. In a word, James possessed no ideal that qualified him to be a
king, much less an Empire-Maker. William did possess such an ideal,
and that is the only reason why he became King of England, vice
James Stuart, absconded.
Next, perhaps, to Henry VII., William was the most business-like
sovereign who has occupied the British throne. With him all men and
things, all beliefs and sentiments, were subordinated to the
achievement of the one great end—the curbing of the power of
France, and consequently the furtherance of political and theological
liberty in Europe. He was, in fact, only incidentally an Empire-Maker,
although without him and without the broad and firm basis of
popular liberty and national strength which he laid down, as it were,
in the doing of his greater work, the building up of the Imperial
fabric would undoubtedly have been long delayed and seriously
impeded.
He got himself made King of Great Britain and Ireland, not
because he wanted to occupy the throne, but because from that
eminence he would be able to look the Grand Monarch more equally
in the face.
We get a luminous insight into the character of the man in his
reply to the Convention or conference of the two Houses of
Parliament which had proposed that his wife as actual and lawful
heir to the throne which her father had forsaken, should occupy it as
queen, and that he should reign by her authority as a sort of Royal
Executive.
“My lords and gentlemen,” he said, “no man can esteem a
woman more than I do the Princess, but I am so made that I cannot
think of holding anything by apron-strings, nor can I think it
reasonable to have any share in the government unless it be put in
my own person, and that for the term of my life. If you think fit to
settle it otherwise I will not oppose you, but will go back to Holland
and meddle no more in your affairs.”
That was the kind of man William of Orange was. He had come
to be a king, and a king he would be or nothing. And so king he
was, and it was not very long before he was to show how well his
self-confidence was justified. He had scarcely seated himself on the
throne before the Parliament, recognising the fact that his work was
something other than merely filling James’s place, deliberately
suggested that he should resume as King of England the hostilities
which he had begun against Louis as Stadtholder of the Netherlands,
and he on his part showed how ready he was to take up the task by
exclaiming, in one of his rare bursts of exultation, after reading the
address:
“This is the first day of my reign!”
This address, however, welcome as it was, was somewhat
belated. For more than a month before it was presented, Louis,
under the pretence of helping the runaway, whom for his own
purposes he affected to believe still lawful King of England, had
committed the gravest of all acts of war, and James had crowned the
disgrace of his flight by the infamy of heading an invasion of British
territory by foreign mercenaries. On the 12th of March, 1689, he
landed at Kinsale as enemy and invader of his own country,
convoyed by fifteen French men-of-war, and supported by 2,500
French troops.
The story of this Irish war needs no re-telling here, save in so far
as it brings out the contrast between William and James as the Fit
and the Unfit for the doing of that work which had just then got to
be done if England was not to sink back to the degrading position of
a French dependency, and if the way of future progress and Imperial
expansion was to be left open. William no sooner saw that the scene
of the fight for constitutional liberty and religious freedom had
shifted for the time being from the Low Countries to Ireland than he
sent Marshal Schomberg, who was then one of the most skilful
soldiers in Europe, with an army of sixteen thousand men to the
scene of action.
Meanwhile the heroically stubborn resistance which has won
immortal fame for the men of Londonderry had proved, not only to
James and his foreign mercenaries, but to Louis himself and all
Europe, that the struggle which was just then renewed was no mere
war of dynasties, and that something very much greater than the
mere question as to who should be king of England had got to be
decided before the trouble was over.
James in Ireland and Louis in France stood for the already
discredited and exploded doctrine of the divine right of kings to rule
as they pleased because they were the sons of their fathers; for the
dark tyranny of Rome, now almost equally discredited; and for the
domination of Europe by the French autocracy. In Holland and
England and Germany William and his allies stood for the very
reverse of all this, so that it was not only the destinies of the United
Kingdom, but those of the greater part of the civilised world that had
to be decided, and it was by procuring through mingled victory and
defeat, confronted by powerful enemies abroad and by conspiracy
and threatened assassination at home, that the worthy descendant
of William the Silent proved his real right divine as king of these
realms and champion of those principles of which the British Empire
of to-day is the concrete expression.
It was really on the shores of an insignificant Irish stream that
William fought and won the battle of European liberty. But before he
did this he had another battle to fight, as it were, in front of his
newly-given throne.
His reign, unhappily, saw the commencement of that system of
government which an intelligent Chinese Minister to the Court of St.
James’ once described as “the election of one party to do the
business of the nation, and of another to stop them doing it.” In
other words, it was William’s fate, among all his other difficulties, to
have to contend with the bitter and usually dishonest strife of
Parliamentary parties, and so keen did this strife become after the
foreign enemy had actually landed on British soil, that he was even
then on the point of throwing up the whole business in disgust, and
going back to Holland to fight his battles out there.
What would have happened if he had done so is anything but a
pleasant subject for speculation. Happily, at the eleventh hour he
refused to acknowledge himself beaten. Sick of the strife of words
and longing for the reality of deeds, he announced his intention to
place himself at the head of the English forces in Ireland, “and with
the blessing of God Almighty endeavour to reduce that kingdom that
it may no longer be a charge to this.”
In this we may see more than the expression of a pious hope. As
statesman and soldier William had seen that Ireland was the back-
door of Great Britain, and that so long as it remained open so long
would the whole kingdom be vulnerable to foreign invasion, and so
he went to close it.
It was a strange position for any man to be placed in. He was
going to fight for everything that he held dear. He knew that if he
lost in Ireland he must lose also in England and the Netherlands, but
he was also going to fight against the father of the woman whom he
had now come to love so dearly that her death, when it happened,
came nearer to wrecking his imperial intellect than all the other trials
and troubles of his laborious and almost joyless life. He had no
feeling of personal enmity against James as he had against Louis,
and it was duty, and duty alone, which took him to the Irish war.
Almost the last words that he said to his wife concerning the enemy
whom he was about to meet on the battlefield were:
“God send that no harm may come to him!”
Mr. Traill has thus tersely summed up the condition of affairs at
this moment: “Ireland in the hands of a hostile army, the shores of
England threatened by a hostile fleet, a dangerous conspiracy only
detected on the eve of success, a formidable insurrection imminent
in the country he was leaving behind him....”
And yet, gloomy as the outlook seemed, his spirits rose as they
ever did when he saw the moment for doing instead of talking draw
near, and Bishop Burnett tells us that he said to him on the eve of
his departure: “As for me, but for one thing I should enjoy the
prospect of being on horseback and under canvas again, for I am
sure that I am fitter to direct a campaign than to manage your
Houses of Lords and Commons.”
These words were well worthy of the man who, not many days
later, quietly sat down to breakfast in the open air beside Boyne
Water, within full sight of the enemy and within easy range of their
guns. Breakfast over, he mounted his horse and was promptly fired
at. The first shot from two field-pieces which had been trained on
him and his staff killed a man and two horses. The second grazed
his shoulder and made him reel in his saddle.
“There was no need for any bullet to come nearer than that!”
was his remark on the occurrence. Certainly not many bullets have
ever come nearer to changing the history of Britain, and therefore of
the British Empire, than that one.
MADE HIM REEL IN HIS SADDLE.

After the wound had been dressed, instead of taking the rest
which a good many strong men would have taken, this consumptive
and asthmatic invalid re-mounted his horse and remained until
nightfall in the saddle, making his dispositions for the battle of the
morrow, and attending to every detail himself. His prudent uncle and
father-in-law, apparently bent on fulfilling William’s pious wish, was
meanwhile taking very good care to keep himself out of harm’s way.
“MEN OF ENNISKILLEN, WHAT WILL YOU DO FOR ME?” HE
CRIED.

The battle itself, which, as every one knows, was fought on the
1st of July, brought out with startling clearness the contrast between
the man who was king in his own right and the man who called
himself king because his name was James Stuart.
“Men of Enniskillen, what will you do for me?” he cried at the
critical moment of the fight, when Caillemot and Schomberg, his two
best captains, had been killed, and he, drawing his sword and
swinging it aloft with his wounded arm, led his trusty Dutch guards
and Ulstermen against the Irish centre. James, meanwhile, having
watched the first part of the fight on which all his fortunes depended
from the safe eminence of the Hill of Donore, had already given up
for lost the day which he had done nothing to win, and was making
the best of his way to Dublin, whence, in due course, leaving the
beaten and demoralised rabble that had once been his army to its
fate, he fled to the congenial ignominy of his safe retreat at St.
Germain, and the fostering care of his country’s worst enemy.
The Battle of the Boyne not only settled the fate of the Stuart
dynasty for good; it decided the question whether this country was
to be ruled by a feeble despotism under the patronage of France, or
by that constitutional monarchy under which Great Britain has so
worthily proved her title to be called the Mother of Free Nations, and
in winning this battle and deciding this all-important question,
William of Orange won the right to be counted among the wisest
and strongest of our Empire-Makers. The disgusted Irishmen, too,
had some reason on their side when they said to the victors after
the battle: “Change leaders, and we’ll fight you again!”
The story of his wars in those countries which have been aptly
termed the cockpit of Europe is the story of the continuation of that
work which he came to England to do; not, as has already been
pointed out, for England as a country, but for the establishment of
those principles for which the British Constitution, of which he was
one of the makers, stands. Ignorant or prejudiced critics have
accused him of sacrificing English blood and treasure to the
furtherance of his own ambition. The fact is that he employed them
upon the best and most necessary work that there was for them to
do just then.
“Look at my brave English!” he said to the Elector of Bavaria one
day during the siege of Namur, while a British regiment was carrying
the outworks on one side of the city. But they were doing more than
carrying earthworks. They were fighting for the principles which their
descendants crowned with everlasting glory at Trafalgar and
Waterloo. They were showing the soldiers and generals of France,
then held to be the best in the world, the sort of stuff that they were
made of, and giving promise of future prowess that was soon to be
splendidly redeemed at Blenheim and Ramillies, Oudenarde and
Malplaquet.
It was a singular war, and by all the rules of warfare the issue
should have been the reverse of what it was. But again and again
William’s wonderful genius and indomitable persistence snatched
victory out of defeat, and turned disaster into advantage, until at last
the Grand Monarch himself had to confess the power of the enemy
whom he had once thought so insignificant, and the signing of the
Treaty of Ryswick left William triumphant if somewhat dissatisfied.
The results would no doubt have been much greater if William
could have had his own way, and if the strife of parties in the British
Parliament had not so sorely crippled him. But at least he had the
satisfaction of knowing before he died that, whereas a few months
before the French men-of-war had with impunity insulted and
threatened the English coasts, and landed a small army on Irish soil,
a few months afterwards every invader had been driven from British
ground, and the French fleet almost destroyed, while the
Mediterranean, on which British ships had sailed only by sufferance,
was now well on the way to becoming a British lake.
And yet, in spite of all the triumphs that he had won over so
many difficulties and so many dangers, and in spite of the
consciousness of work well and nobly, if quietly and
unostentatiously, done, William’s last days, like those of many
another man who has deserved well of the world, were full of sorrow
and suffering.
The death of his now adored queen had so shaken his mighty
nature that for some days his reason was despaired of, and there
can be no doubt but that it hastened his own end. And yet, weak
and far advanced in disease as he was when he went out for that
fatal ride from Kensington to Hampton Court, he was even then
going a-hunting. The brutal Jacobite toast: “To the little gentleman
in black velvet who works underground!” still serves to remind us of
the mole-hill over which his horse stumbled and fell, breaking his
rider’s collar-bone, and inflicting the death-wound which he had
escaped on a score of battle-fields.
His death was worthy of his life, for it was the death of a brave,
patient man and a Christian gentleman. No doubt he himself would
have preferred to have died at the head of a charge, or in the thick
of an assault on a French fortress, but his destiny ordered it
otherwise, and the man who had a hundred times faced death in the
most reckless fashion for the purpose of inspiring his followers with
his own courage and enthusiasm, died quietly in his bed, leaving
behind him the greatest work ever done by an individual British
sovereign, and a fame which, but for the one dark and inexplicable
blot of Glencoe, is as fairly entitled to be called spotless as that of
any man who ever sat upon a throne and accomplished great things
with such means as came to his hand.
VI
JAMES COOK,
CIRCUMNAVIGATOR
VI

JAMES COOK

O NCE more I am going to ask you to take your seat with me on


the ideal equivalent of the Magic Carpet and skim across
another time-gulf some half-century wide. This time we alight on the
morning of Monday, July 5, 1742, before the door of a double-
fronted shop, one side of which is devoted to the sale of groceries
and the other to the drapery business. This shop is situated in a little
village on the Yorkshire coast a few miles from Whitby, Staithes, or
more exactly The Staithes, so called from the local name for a pier
or sea-wall of wood jutting out a few feet into the German Ocean,
and built partly to protect the little bay from the North Sea rollers
and partly to afford accommodation for the fishing-boats and
colliers.

The shop belongs to a substantial citizen of Staithes named


Saunderson, and this morning Mr. Saunderson is a very angry man.
In fact, if we go into the shop, which is not yet open, we shall find
him with a cane or some similar weapon in his hand, leaning behind
the counter and hitting blindly at a bed there is beneath it, shouting
the while sundry excellent maxims on the virtue of early rising,
especially modified for the benefit of apprentices.
But no response comes from the bed, and Mr. Saunderson
stoops down to make closer investigation. The bed is empty, and the
fact dawns on him that his last apprentice has followed the example
of all the others and run away to sea. It was a very common event
on the Yorkshire coast in those days, but this particular running
away was destined to be a very memorable one for the world, for
the lad who, instead of being in the bed under the counter, was just
then striding rapidly away over the fields to Whitby with one extra
shirt and a jack-knife for his sole possessions, was James Cook, a
name as dear to the lovers of the romance of travel and adventure
as Robinson Crusoe, and one of infinitely more importance in the
annals of mankind.
In following his fortunes, so far as the brief limits of such a
sketch as this will permit, we shall bid a perhaps welcome adieu for
a while to the roar of guns and the shock of battle, to the blaze of
burning towns and the fierce cries ringing along the decks of
captured treasure-ships, to watch the contest of a clear head and a
strong will against those foes which may be overcome without
bloodshed, although not always without loss of life—the hidden
dangers of unknown oceans strewn with uncharted reefs and shoals
lying in wait for unwary keels, the sudden hurricanes of the Tropics,
and the storms and fogs and the floating ice-navies of the far North
and South. It was these that Captain Cook went out to fight and
overcome, and in doing so to prove eloquently that:

“Peace hath her victories no less renowned than war.”

Nevertheless there are certain points of likeness between James


Cook, Geographer and Circumnavigator, and that other
Circumnavigator, Francis Drake, Pirate and Scourge of Spain. Both
began life as ship-boys, and both rose, by sheer ability and strength
of purpose, far above their original station in life to positions of
command in the service of their country. Both were men of iron will,
far-reaching design, unshakeable self-reliance, and passionate
temper, and, lastly, both were possessed by that irresistible spirit of
roving and adventure which, when it once seizes a man, but seldom
lets him rest in peace. In short, though the vocation of one was
piracy and war, and that of the other the peaceful, but none the less
adventurous service of science, both were stamped with the
supreme and essential characteristics of the Empire-Maker.
Naturally, the world had changed a good deal by the time James
Cook started out to add so enormously to men’s knowledge of it.
Spain had fallen from her high estate and was living in slothful ease
on the dregs and lees of that strong wine which she had drunk to
intoxication in the golden days of Cortez and Pizarro. But Britain, no
longer only England, had become Great Britain, and was fast
expanding into Greater Britain. Cowley, Dampier, Clapperton and
Anson had circumnavigated the globe more than once, and people
were beginning to have something like a definite notion of how very
big a place was this world which now seems so small to us. The
Imperial Idea was beginning to take hold of men’s minds. They
wanted to know, not so much how big the world was, but what
other unknown lands might be lying waiting for the discoverer,
hidden away among the vast expanses which were still an utter
blank upon the map.
The maritime nations of the world, too, and Britain, now
foremost among them, had unconsciously taken a very great stride
along the pathway of real progress, and they were beginning to
grasp the higher ideal of colonisation as distinguished from mere
conquest, and to James Cook belongs the high honour, if not of
discovering, at least of first definitely locating and in part mapping
out the greatest of all the British colonies.
Indeed, it may be said that, in sober fact, he added a whole
continent to the British Empire, and that without the striking of a
single blow or the loss of a single life in battle.
The first few years of James Cook’s seafaring life were eventless,
just as Francis Drake’s were, but for all that he, like Gloriana’s Little
Pirate, was doing that minor but no less essential part of his life-
work which was the necessary preparation for the greater. He was
doing his work first as ship’s boy, then as sailor before the mast,
then as second mate, first mate, and so on up the laborious ladder
which was to lead him in the end to an unequalled eminence among
mariners.
Thus for thirteen years he served what may be called his
apprenticeship to his life’s work; learning in the most practical of all
schools, a North Sea collier of the eighteenth century, not only the
science of seamanship in all its details, but also what was hardly less
important—that science of taking things as they came, of looking
upon hardship, privation and danger as the commonplaces of a
seaman’s life, incidents in his day’s work, as it were, and as such
scarcely worth even the mention, and hence much less worth
troubling about.
A curiously instructive fact strikes one in contrasting Captain
Cook’s own account of his voyages with those of others, such as
Anderson and Gilbert, who sailed with him. They expatiate largely on
the miseries of heat and cold, ice and mist, the almost uneatable
character of the sea-fare of those days, disease among the crew,
and so on; but Captain Cook hardly ever mentions them, saving only
the scurvy, of which more hereafter.
But there was something else that James Cook had already
learnt long ago while he was yet a boy. When he was a lad of six or
seven he had been set to work on a farm belonging to a man named
William Walker, and this William had a wife named Mary who, taking
a fancy to the lad, taught him his letters and encouraged him to
read, and so, without knowing it, put into his hands the talisman
which was to win his way to future greatness. She not only aroused
in him that passion for reading which distinguished him among the
sailors of his time, but she gave him what might have been the only
means of gratifying it, for not every farm-lad and ship’s-boy of the
middle of the eighteenth century had learnt, or ever did learn, to
read and write.
It may have been that James Cook’s latent ambition had never
looked beyond the possibility of becoming master of one of the
vessels of which he had been mate, and it is also possible that he
might never in reality have been anything more, but it so happened
that his ship, the Friendship, was lying in London river in May, 1756,
and that at the same time the war with France, which had been
brewing for a year, broke out.
As usual the Press Gang set instantly to work, and now came
Cook’s chance. He was mate of a ship, albeit only a collier brig; still
he was a thorough seaman, an excellent navigator, and, more than
that, he seems to have known something of the theory as well as
the practice of his science. These accomplishments, however, did not
put him beyond the reach of the Press Gang.
Now, in those days there were two ranks of seamen before the
mast in the King’s navy—the pressed man, who might be anything
from a raw land-lubber to an escaped convict, and the volunteer,
who was probably and usually a good sailor, if not something better,
as Cook was, and he, guided either by inspiration or deliberate
resolve, eluded the Press Gang by offering himself as a volunteer,
and so in due course took his rating as able-seaman before the mast
on board his Majesty’s frigate Eagle, of sixty guns, of which shortly
afterwards the good genius of his life, Sir Hugh Palliser, was
appointed captain.
During the next four years there was fighting, but we have no
record of any share that Cook took in it. What we do know is that by
the time he was thirty he had risen to the rank of master of the
Mercury, a King’s ship which went with the fleet to the St. Lawrence
at a very critical juncture in British colonial history.
So far it would appear that he had worked himself up by sheer
ability and industry, but now his chance was to come. The river St.
Lawrence at that time had never been surveyed, and it was
absolutely necessary that soundings should be taken and the river
correctly charted before the fleet could go in and with its guns cover
Wolfe’s attack on Quebec. The all-important work was entrusted to
the master of the Mercury, and although the river was swarming
with the canoes of hostile Indians in the service of the French, and
though he had to do his work at night, he did it so thoroughly that
not only did the fleet go in and out again with perfect safety, but the
work has needed but little re-doing from that day to this.
Thus did James Cook, not as sailor or fighting-man, but as good
mariner and skilful workman play his first part as Empire-Maker, and
in an unostentatious fashion contribute his share towards the
capture of Quebec and the acquisition of one of the widest and
fairest portions of Greater Britain.
He was at this time, as has been said, only thirty. As regards the
outer aspect of the man he stood something over six feet, spare,
hard, and active. His face was a good one and suited to the man,
broad forehead, bright, brown, well-set eyes, yet rather small, a
long, well-shaped nose with good nostrils, a firm mouth, and full,
strong chin.
In short, his best portraits show you just the kind of man you
would expect Captain Cook to be. For the rest he was a man of iron
frame, tireless at work, resting only when it was a physical necessity,
with few friends and fewer confidants, cool of judgment save during
his rare and deplorable fits of passion, self-contained and self-reliant
—just such a sea-king, in short, as we may imagine Heaven to have
commissioned to carry the British flag three times round the world
and to the uttermost parts of the known earth, and to plant it on
lands which until then no white man’s eye had seen or foot had
trodden.
In the same year Cook was promoted from the Mercury to the
Northumberland, the Admiral’s flag-ship, and in her he came back to
England, and at St. Margaret’s Church, Barking, married Elizabeth
Batts, a young lady of great beauty and of social standing far above
that of the grocer’s apprentice and collier’s knockabout boy, but not
above that of the Master of a King’s ship. His married life lasted
some seventeen years, and of these he spent a little over four in the
enjoyment of the delights of home.
For the next four years or so he was regularly employed in
surveying and exploring work off the Atlantic coast of America, and
this of itself shows that he had already made his mark in his chosen
profession. But much greater things were now to be in store for him.
It will be remembered how Drake, when he first saw the smooth
waters of the Pacific, prayed God that He would give him life and
leave to sail an English ship on its waters. That prayer had been
granted, and his and many another English ship had crossed the
great Sea of the South.
Meanwhile the realised dream of El Dorado had been replaced in
men’s minds by another, even more vast, shadowy, and splendid.
This was the dream of the Great Southern Continent, and in this
imagination revelled and ran riot. Grave scientists, too,
demonstrated beyond all doubt that there must be such a land far
away to the south since how, without it as a counterpoise to the
continents of the north, was the rolling world to be kept in
equilibrium?
So they took it for granted, laid it down upon the maps, and
wrote glowing descriptions of the varieties of climate, the splendour
of scenery, the wealth of treasures and the strange peoples and
animals that it must of necessity contain. Above all, it would be a
new El Dorado which would not be under the control of Spain.
What more could men want, unless indeed it was the actual
discovery of the Terra Incognita Australis? This was the new world of
which Cook was to be the Columbus. Others had seen parts of it just
as others had seen parts of America before the great Genoese
reached the West Indies, but he was the man who was to do the
work of putting its existence beyond all doubt.
The Royal Society found that there would be a transit of Venus
in the year 1769, and that it would be best observed from some
point in the great Southern Ocean, say Amsterdam Island or the
Marquesas Group, lately discovered by the Dutch and Portuguese,
and as the result of representations made to the King, an expedition
was set on foot to carry out suitable persons to observe it. Of this
expedition James Cook, raised from the rank of master to that of
lieutenant, was placed in command. On his own recommendation
the ship chosen for the purpose was the Endeavour, a Whitby-built
craft of 370 tons, broad of bow and stern and fairly light of draft,
and built for strength and endurance rather than speed.
She sailed, carrying a complement all told of eighty-five men,
from Plymouth on August 26, 1768, which as Cook’s latest
biographer happily remarks, was a Friday, and the starting-day of
what was, all things considered, the most successful voyage of
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like