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

Download Complete (Ebook) Go Standard Library Cookbook by Radomir Sohlich ISBN 9781788475273, 1788475275 PDF for All Chapters

The document provides a comprehensive overview of various eBooks available for download, particularly focusing on programming languages like Go, C++, Python, and .NET. It highlights specific titles, their authors, and ISBNs, along with links for purchasing or downloading. Additionally, it includes information about the Go Standard Library Cookbook, which offers over 120 practical examples for utilizing Go's standard library components.

Uploaded by

spaidspineep
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
88 views

Download Complete (Ebook) Go Standard Library Cookbook by Radomir Sohlich ISBN 9781788475273, 1788475275 PDF for All Chapters

The document provides a comprehensive overview of various eBooks available for download, particularly focusing on programming languages like Go, C++, Python, and .NET. It highlights specific titles, their authors, and ISBNs, along with links for purchasing or downloading. Additionally, it includes information about the Go Standard Library Cookbook, which offers over 120 practical examples for utilizing Go's standard library components.

Uploaded by

spaidspineep
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Download Full Version ebook - Visit ebooknice.

com

(Ebook) Go Standard Library Cookbook by Radomir


Sohlich ISBN 9781788475273, 1788475275

https://ebooknice.com/product/go-standard-library-
cookbook-23378366

Click the button below to download

DOWLOAD EBOOK

Discover More Ebook - Explore Now at ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Go Cookbook: Build modular, readable, and testable


applications in Go by Aaron Torres ISBN 9781783286836,
1783286830
https://ebooknice.com/product/go-cookbook-build-modular-readable-and-
testable-applications-in-go-9992542

ebooknice.com

(Ebook) Go Cookbook: Expert Solutions for Commonly Needed


Go Tasks by Sau Sheong Chang ISBN 9781098122119,
1098122119
https://ebooknice.com/product/go-cookbook-expert-solutions-for-
commonly-needed-go-tasks-53849886

ebooknice.com

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason;


Viles, James ISBN 9781459699816, 9781743365571,
9781925268492, 1459699815, 1743365578, 1925268497
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com

(Ebook) Go Cookbook: Expert Solutions for Commonly Needed


Go Tasks (First Early Release) by Sau Sheong Chang ISBN
9781098122102, 1098122100
https://ebooknice.com/product/go-cookbook-expert-solutions-for-
commonly-needed-go-tasks-first-early-release-38248914

ebooknice.com
(Ebook) The C++ Standard Library by Nicolai M. Josuttis
ISBN 9780321623218, 0321623215

https://ebooknice.com/product/the-c-standard-library-6761728

ebooknice.com

(Ebook) Python Standard Library (Nutshell Handbooks) by


Fredrik Lundh ISBN 9780596000967, 0596000960

https://ebooknice.com/product/python-standard-library-nutshell-
handbooks-1990292

ebooknice.com

(Ebook) The Python Standard Library by Example by


Hellmann, Doug ISBN 9780321767349, 0321767349

https://ebooknice.com/product/the-python-standard-library-by-
example-34854700

ebooknice.com

(Ebook) .NET Framework Standard Library Annotated


Reference by Brad Abrams ISBN 9780321154897, 0321154894

https://ebooknice.com/product/net-framework-standard-library-
annotated-reference-972416

ebooknice.com

(Ebook) The C++ Standard Library: Fourth Edition includes


C++23 by Rainer Grimm

https://ebooknice.com/product/the-c-standard-library-fourth-edition-
includes-c-23-49417210

ebooknice.com
Go Standard Library Cookbook

Over 120 specific ways to make full use of the standard


library components in Golang

Radomír Sohlich

BIRMINGHAM - MUMBAI
Go Standard Library Cookbook
Copyright © 2018 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 or its dealers and distributors, will be held liable for any damages caused or alleged to
have been 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.

Commissioning Editor: Merint Mathew


Acquisition Editor: Aiswarya Narayanan
Content Development Editor: Anugraha Arunagiri
Technical Editor: Subhalaxmi Nadar
Copy Editor: Safis Editing
Project Coordinator: Ulhas Kambali
Proofreader: Safis Editing
Indexer: Rekha Nair
Graphics: Tania Dutta
Production Coordinator: Arvindkumar Gupta

First published: February 2018

Production reference: 1230218

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78847-527-3

www.packtpub.com
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as
well as industry leading tools to help you plan your personal development and advance
your career. For more information, please visit our website.

Why subscribe?
Spend less time learning and more time coding with practical eBooks and Videos
from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

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 service@packtpub.com 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.
Contributors

About the author


Radomír Sohlich received the master's degree in Applied Informatics from Faculty of
Applied Informatics at Tomas Bata University in Zlín. After that, he got a job in a start-up
company as a software developer and worked on various projects, usually based on the
Java platform. Currently, he continues a software developer career as a contractor for a
large international company.

In 2015, he fell in love with Go and kept exploring the endless power and possibilities of the
language. He is passionate about learning new approaches and technology and feels the
same about sharing the knowledge with others.

I'd like to thank my beloved wife and kids for the time they gave me for creating this book.
The next big thank you belongs to Mert Serin, who agreed to review the book and give a
feedback on the content.
About the reviewer
Mert Serin was born in Izmir in 1993, graduated from Hacettepe University in 2016, and
has worked on iOS development since his third year in university. He is currently working
at USIT Inc., a start-up based in Atlanta, GE, as a full stack developer.

Packt is searching for authors like you


If you're interested in becoming an author for Packt, please visit authors.packtpub.com and
apply today. We have worked with thousands of developers and tech professionals, just
like you, to help them share their insight with the global tech community. You can make a
general application, apply for a specific hot topic that we are recruiting an author for, or
submit your own idea.
Table of Contents
Preface 1

Chapter 1: Interacting with the Environment 6


Introduction 6
Retrieving the Golang version 7
Getting ready 7
How to do it... 7
How it works... 8
Accessing program arguments 9
How to do it... 9
How it works... 10
There's more… 10
Creating a program interface with the flag package 11
How to do it... 11
How it works… 13
There's more… 14
Getting and setting environment variables with default values 14
How to do it… 14
How it works… 17
Retrieving the current working directory 18
How to do it... 18
How it works… 19
Getting the current process PID 20
How to do it… 20
How it works… 21
Handling operating system signals 21
How to do it… 22
How it works… 23
Calling an external process 24
Getting ready 24
How to do it… 25
Table of Contents

How it works… 27
See also 28
Retrieving child process information 28
Getting ready 28
How to do it… 28
How it works… 31
See also 31
Reading/writing from the child process 31
Getting ready 31
How to do it… 32
How it works… 38
Shutting down the application gracefully 39
How to do it… 39
How it works… 42
See also 42
File configuration with functional options 42
How to do it... 42
How it works... 45
Chapter 2: Strings and Things 46
Introduction 46
Finding the substring in a string 47
How to do it... 47
How it works... 48
See also 48
Breaking the string into words 49
How to do it... 49
How it works... 52
There's more... 53
Joining the string slice with a separator 53
How to do it... 53
How it works... 55
There's more... 56
Concatenating a string with writer 56
How to do it... 56
How it works... 58

[ ii ]
Table of Contents

There's more... 58
Aligning text with tabwriter 59
How to do it... 60
How it works... 61
Replacing part of the string 61
How to do it... 61
How it works... 63
There's more... 64
Finding the substring in text by the regex pattern 64
How to do it... 64
How it works... 65
See also 66
Decoding a string from the non-Unicode charset 66
How to do it... 66
How it works... 68
Controlling case 69
How to do it... 69
How it works... 71
Parsing comma-separated data 71
How to do it... 72
How it works... 74
Managing whitespace in a string 75
How to do it... 75
How it works... 76
See also 77
Indenting a text document 77
How to do it... 78
How it works... 79
See also 79
Chapter 3: Dealing with Numbers 80
Introduction 80
Converting strings to numbers 81
How to do it... 81
How it works... 82
Comparing floating-point numbers 83

[ iii ]
Table of Contents

How to do it... 83
How it works... 85
Rounding floating-point numbers 86
How to do it... 86
How it works... 87
Floating-point arithmetics 88
How to do it... 88
How it works... 89
There's more... 89
See also 90
Formatting numbers 90
How to do it... 90
How it works... 92
There's more... 93
Converting between binary, octal, decimal, and hexadecimal 93
How to do it... 93
How it works... 95
Formatting with the correct plurals 95
Getting ready 95
How to do it... 95
How it works... 97
There's more... 97
Generating random numbers 98
How to do it... 98
How it works... 99
Operating complex numbers 100
How to do it... 100
How it works... 101
Converting between degrees and radians 102
How to do it... 102
How it works... 103
Taking logarithms 104
How to do it... 104
How it works... 105
Generating checksums 105

[ iv ]
Visit https://ebooknice.com to
discover a wide range of
eBooks across various genres.
Enjoy exclusive deals and
discounts to enhance your
reading experience. Start your
digital reading journey today!
Table of Contents

How to do it... 105


How it works... 108
Chapter 4: Once Upon a Time 109
Introduction 109
Finding today's date 110
How to do it... 110
How it works... 110
See also 111
Formatting date to string 111
How to do it... 111
How it works... 112
See also 113
Parsing the string into date 113
How to do it... 113
How it works... 115
Converting dates to epoch and vice versa 115
How to do it... 115
How it works... 116
Retrieving time units from the date 117
How to do it... 117
How it works... 118
Date arithmetics 118
How to do it... 118
How it works... 119
Finding the difference between two dates 120
How to do it... 120
How it works... 121
Converting between time zones 121
How to do it... 122
How it works... 123
Running the code block periodically 123
How to do it... 123
How it works... 124
Waiting a certain amount of time 125
How to do it... 125

[v]
Table of Contents

How it works... 126


Timeout long-running operations 127
How to do it... 127
How it works... 128
There's more... 129
Serializing the time and date 129
How to do it... 129
How it works... 130
Chapter 5: In and Out 131
Introduction 131
Reading standard input 132
How to do it... 132
How it works... 135
Writing standard output and error 135
How to do it... 135
How it works... 137
Opening a file by name 137
How to do it... 137
How it works... 139
Reading the file into a string 139
How to do it... 139
How it works... 141
Reading/writing a different charset 141
How to do it... 141
How it works... 143
See also 143
Seeking a position within a file 143
How to do it... 143
How it works... 146
Reading and writing binary data 147
How to do it... 147
How it works... 148
Writing to multiple writers at once 149
How to do it... 149
How it works... 150

[ vi ]
Table of Contents

Piping between writer and reader 150


How to do it... 150
How it works... 151
Serializing objects to binary format 152
How to do it... 152
How it works... 154
Reading and writing ZIP files 154
How to do it... 154
How it works... 156
Parsing a large XML file effectively 157
How to do it... 157
How it works... 159
Extracting data from an incomplete JSON array 159
How to do it... 159
How it works... 161
Chapter 6: Discovering the Filesystem 162
Introduction 162
Getting file information 163
How to do it... 163
How it works... 164
Creating temporary files 164
How to do it... 164
How it works... 165
Writing the file 166
How to do it... 166
How it works... 167
Writing the file from multiple goroutines 167
How to do it... 167
How it works... 169
Listing a directory 169
How to do it... 169
How it works... 171
Changing file permissions 172
How to do it... 172
How it works... 173

[ vii ]
Table of Contents

Creating files and directories 173


How to do it... 173
How it works... 174
Filtering file listings 175
How to do it... 175
How it works... 176
See also 177
Comparing two files 177
How to do it... 177
How it works... 180
Resolving the user home directory 180
How to do it... 180
How it works... 181
Chapter 7: Connecting the Network 182
Introduction 182
Resolving local IP addresses 183
How to do it... 183
How it works... 184
Connecting to the remote server 185
How to do it... 185
How it works... 186
Resolving the domain by IP address and vice versa 187
How to do it... 187
How it works... 188
Connecting to the HTTP server 188
How to do it... 189
How it works... 191
See also 191
Parsing and building a URL 192
How to do it... 192
How it works... 193
Creating an HTTP request 193
How to do it... 193
How it works... 195
Reading and writing HTTP headers 195

[ viii ]
Table of Contents

How to do it... 196


How it works... 197
Handling HTTP redirects 197
How to do it... 198
How it works... 200
Consuming the RESTful API 200
How to do it... 200
How it works... 203
Sending a simple email 203
Getting ready 203
How to do it... 203
How it works... 205
Calling the JSON-RPC service 206
How to do it... 206
How it works... 208
Chapter 8: Working with Databases 209
Introduction 209
Connecting the database 210
Getting ready 210
How to do it... 210
How it works... 211
Validating the connection 212
Getting ready 212
How to do it... 212
How it works... 214
Executing statements 214
Getting ready 214
How to do it... 214
How it works... 217
Operations with prepared statements 217
Getting ready 217
How to do it... 217
How it works... 220
Canceling the pending query 221
Getting ready 221

[ ix ]
Table of Contents

How to do it... 221


How it works... 223
Reading query result metadata 224
Getting ready 224
How to do it... 224
How it works... 226
Retrieving data from a query result 227
Getting ready 227
How to do it... 227
How it works... 230
Parsing the query result into a map 230
Getting ready 230
How to do it... 230
How it works... 233
Handling transactions 234
Getting ready 234
How to do it... 234
How it works... 237
Executing stored procedures and functions 237
Getting ready 237
How to do it... 238
How it works... 239
Chapter 9: Come to the Server Side 241
Introduction 241
Creating the TCP server 242
How to do it... 242
How it works... 243
Creating the UDP server 244
How to do it... 244
How it works... 245
Handling multiple clients 246
How to do it... 246
How it works... 248
Creating the HTTP Server 248
How to do it... 248

[x]
Table of Contents

How it works... 249


Handling HTTP requests 250
How to do it... 250
How it works... 251
Creating HTTP middleware layer 252
How to do it... 252
How it works... 253
Serving static files 254
How to do it... 254
How it works... 256
Serving content generated with templates 256
How to do it... 256
How it works... 257
Handling redirects 258
How to do it... 258
How it works... 259
Handling cookies 260
How to do it... 260
How it works... 262
Gracefully shutdown the HTTP server 263
How to do it... 263
How it works... 265
Serving secured HTTP content 265
Getting ready 265
How to do it... 266
How it works... 267
Resolving form variables 267
How to do it... 267
How it works... 268
Chapter 10: Fun with Concurrency 269
Introduction 269
Synchronizing access to a resource with Mutex 270
How to do it... 270
How it works... 272
Creating map for concurrent access 272

[ xi ]
Table of Contents

How to do it... 273


How it works... 274
Running a code block only once 274
How to do it... 275
How it works... 276
Pooling resources across multiple goroutines 277
How to do it... 277
How it works... 278
Synchronizing goroutines with WaitGroup 279
How to do it... 279
How it works... 280
Getting the fastest result from multiple sources 281
How to do it... 281
How it works... 283
Propagating errors with errgroup 283
How to do it... 284
How it works... 285
Chapter 11: Tips and Tricks 286
Introduction 286
Logging customization 287
How to do it... 287
How it works... 288
Testing the code 288
How to do it... 288
How it works... 290
See also 290
Benchmarking the code 290
How to do it... 290
How it works... 291
See also 292
Creating subtests 292
How to do it... 292
How it works... 293
See also 294
Testing the HTTP handler 294

[ xii ]
Table of Contents

How to do it... 294


How it works... 296
Accessing tags via reflection 296
How to do it... 296
How it works... 297
Sorting slices 297
How to do it... 298
How it works... 299
Breaking HTTP handlers into groups 299
How to do it... 300
How it works... 301
Utilizing HTTP/2 server push 302
Getting ready 302
How to do it... 302
How it works... 304
Other Books You May Enjoy 305

Index 308

[ xiii ]
Preface
Thanks for giving this book a chance! This book is a guide that takes you through the
possibilities of the Go standard library, which has a lot of out-of-the-box functionality and
solutions. Note that the solutions covered in the book are mainly simple demonstrations of
how the standard library implementation is used and how it works. These recipes are
meant to provide a starting point for you to work out how to solve your specific problem
rather than solve the problem completely.

Who this book is for


This book is for those who want to strengthen the basics and reveal hidden parts of the Go
standard library. The book expects readers to have the elementary knowledge of Go. For
some recipes, a basic understanding of HTML, operating systems, and networking will be
helpful.

What this book covers


Chapter 1, Interacting with the Environment, explores how your code can interact with the
operating system environment. The use of command-line flags and arguments, consuming
signals, and working with child processes are also covered.

Chapter 2, Strings and Things, goes through common operations on strings, from simple
searching for substrings to formatting text to tabs.

Chapter 3, Dealing with Numbers, sheds light on basic conversions and number formatting
options. Operations with large numbers and the correct use of plurals within output
messages are covered.

Chapter 4, Once Upon a Time, puts the time package under the magnifying glass and covers
formatting, arithmetics, and running code for given time period or after a certain delay.

Chapter 5, In and Out, covers I/O operations that utilize standard Go interfaces. Besides the
basic I/O, the chapter also covers some useful serialization formats and how to handle them.
Visit https://ebooknice.com to
discover a wide range of
eBooks across various genres.
Enjoy exclusive deals and
discounts to enhance your
reading experience. Start your
digital reading journey today!
Preface

Chapter 6, Discover the Filesystem, discusses working with the filesystem, including listing
the folders, reading and changing the file attributes, and comparing files side by side.

Chapter 7, Connect the Network, showcases the client-side implementations for connecting
the TCP and UDP server, along with the use of SMTP, HTTP, and JSON-RPC .

Chapter 8, Working with Databases, focuses on common database tasks such as data selection
and extraction, transaction handling and execution, and the shortcomings of stored
procedures.

Chapter 9, Come to the Server Side, provides a view on networking from the server's
perspective. TCP, UDP, and HTTP server basics are presented.

Chapter 10, Fun with Concurrency, deals with mechanisms of synchronization and
concurrent access to resources.

Chapter 11, Tips and Tricks, comes with useful tips for testing and improving the HTTP
server implementation and shows the benefits of HTTP/2 push.

To get the most out of this book


Although the Go programming platform is cross-platform, the recipes in the book usually
assumes a Unix-based operating system, or at least that some common Unix utilities are
available for execution. For Windows users, the Cygwin or GitBash utilities could be useful.
The sample code works best with this setup:

Unix-based environment
A version of Go equal to or greater than 1.9.2
An internet connection
Read, write, and execute permissions on a folder where the sample code will be
created and executed

Download the example code files


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

[2]
Preface

You can download the code files by following these steps:

1. Log in or register at www.packtpub.com.


2. Select the SUPPORT tab.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box and follow the onscreen
instructions.

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

The code bundle for the book is also hosted on GitHub


at https://github.com/PacktPublishing/Go-Standard-Library-Cookbook. In case there's
an update to the code, it will be updated on the existing GitHub repository.

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

Conventions used
There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames,
file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an
example: "Verify that your GOPATH and GOROOT environmental variables are set properly."

A block of code is set as follows:


package main
import (
"log"
"runtime"
)

[3]
Preface

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 (
"log"
"runtime"
)

Bold: Indicates a new term, an important word, or words that you see onscreen. For
example, words in menus or dialog boxes appear in the text like this.

Warnings or important notes appear like this.

Tips and tricks appear like this.

Sections
In this book, you will find several headings that appear frequently (Getting ready, How to do
it..., How it works..., There's more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows:

Getting ready
This section tells you what to expect in the recipe and describes how to set up any software
or any preliminary settings required for the recipe.

How to do it…
This section contains the steps required to follow the recipe.

How it works…
This section usually consists of a detailed explanation of what happened in the previous
section.

[4]
Preface

There's more…
This section consists of additional information about the recipe in order to make you more
knowledgeable about the recipe.

See also
This section provides helpful links to other useful information for the recipe.

Get in touch
Feedback from our readers is always welcome.

General feedback: Email feedback@packtpub.com and mention the book title in the
subject of your message. If you have questions about any aspect of this book, please email
us at questions@packtpub.com.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you have found a mistake in this book, we would be grateful if you would
report this to us. Please visit www.packtpub.com/submit-errata, selecting your book,
clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the internet, we
would be grateful if you would provide us with the location address or website name.
Please contact us at copyright@packtpub.com with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in
and you are interested in either writing or contributing to a book, please visit
authors.packtpub.com.

Reviews
Please leave a review. Once you have read and used this book, why not leave a review on
the site that you purchased it from? Potential readers can then see and use your unbiased
opinion to make purchase decisions, we at Packt can understand what you think about our
products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

[5]
Interacting with the
1
Environment
In this chapter, the following recipes are covered:

Retrieving the Golang version


Accessing program arguments
Creating a program interface with the flag package
Getting and setting environment variables with default values
Retrieving the current working directory
Getting the current process PID
Handling operating system signals
Calling an external process
Retrieving child process information
Reading/writing from the child process
Shutting down the application gracefully
File configuration with functional options

Introduction
Every program, once it is executed, exists in the environment of the operating system. The
program receives input and provides output to this environment. The operating system also
needs to communicate with the program to let it know what's happening outside. And
finally, the program needs to respond with appropriate actions.
Interacting with the Environment Chapter 1

This chapter will walk you through the basics of the discovery of the system environment,
the program parameterization via program arguments, and the concept of the operating
system signals. You will also learn how to execute and communicate with the child process.

Retrieving the Golang version


While building a program, it is a good practice to log the environment settings, build
version, and runtime version, especially if your application is more complex. This helps you
to analyze the problem, in case something goes wrong.

Besides the build version and, for example, the environmental variables, the Go version by
which the binary was compiled could be included in the log. The following recipe will show
you how to include the Go runtime version into such program information.

Getting ready
Install and verify the Go installation. The following steps could help:

1. Download and install Go on your machine.


2. Verify that your GOPATH and GOROOT environmental variables are set properly.
3. Open your Terminal and execute go version. If you get output with a version
name, then Go is installed properly.
4. Create a repository in the GOPATH/src folder.

How to do it...
The following steps cover the solution:

1. Open the console and create the folder chapter01/recipe01.


2. Navigate to the directory.
3. Create the main.go file with the following content:

package main
import (
"log"
"runtime"
)
const info = `

[7]
Interacting with the Environment Chapter 1

Application %s starting.
The binary was build by GO: %s`

func main() {
log.Printf(info, "Example", runtime.Version())
}

4. Run the code by executing the go run main.go.


5. See the output in the Terminal:

How it works...
The runtime package contains a lot of useful functions. To find out the Go runtime version,
the Version function could be used. The documentation states that the function returns the
hash of the commit, and the date or tag at the time of the binary build.

The Version function, in fact, returns the runtime/internal/sys .The


Version constant. The constant itself is located in
the $GOROOT/src/runtime/internal/sys/zversion.go file.

This .go file is generated by the go dist tool and the version is resolved by
the findgoversion function in the go/src/cmd/dist/build.go file, as explained next.

The $GOROOT/VERSION takes priority. If the file is empty or does not exist,
the $GOROOT/VERSION.cache file is used. If the $GOROOT/VERSION.cache is also not
found, the tool tries to resolve the version by using the Git information, but in this case, you
need to initialize the Git repository for the Go source.

[8]
Interacting with the Environment Chapter 1

Accessing program arguments


The most simple way to parameterize the program run is to use the command-line
arguments as program parameters.

Simply, the parameterized program call could look like this: ./parsecsv user.csv
role.csv. In this case, parsecsv is the name of the executed binary and user.csv and
role.csv are the arguments, that modify the program call (in this case it refers to files to be
parsed).

How to do it...
1. Open the console and create the folder chapter01/recipe02.
2. Navigate to the directory.
3. Create the main.go file with the following content:

package main
import (
"fmt"
"os"
)

func main() {

args := os.Args

// This call will print


// all command line arguments.
fmt.Println(args)

// The first argument, zero item from slice,


// is the name of the called binary.
programName := args[0]
fmt.Printf("The binary name is: %s \n", programName)

// The rest of the arguments could be obtained


// by omitting the first argument.
otherArgs := args[1:]
fmt.Println(otherArgs)

for idx, arg := range otherArgs {


fmt.Printf("Arg %d = %s \n", idx, arg)

[9]
Interacting with the Environment Chapter 1

}
}

4. Build the binary by executing go build -o test.


5. Execute the command ./test arg1 arg2. (Windows users can run test.exe
arg1 arg2).
6. See the output in the Terminal:

How it works...
The Go standard library offers a few ways to access the arguments of the program call. The
most generic way is to access the arguments by the Args variable from the OS package.

This way you can get all the arguments from the command line in a string slice. The
advantage of this approach is that the number of arguments is dynamic and this way
you can, for example, pass the names of the files to be processed by the program.

The preceding example just echoes all the arguments that are passed to the program.
Finally, let's say the binary is called test and the program run is executed by the Terminal
command ./test arg1 arg2.

In detail, the os.Args[0] will return ./test. The os.Args[1:] returns the rest of the
arguments without the binary name. In the real world, it is better to not rely on the number
of arguments passed to the program, but always check the length of the argument array.
Otherwise, naturally, if the argument on a given index is not within the range, the program
panics.

[ 10 ]
Exploring the Variety of Random
Documents with Different Content
The Project Gutenberg eBook of Over the
Santa Fé Trail, 1857
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: Over the Santa Fé Trail, 1857

Author: William Barclay Napton

Release date: December 20, 2023 [eBook #72461]

Language: English

Original publication: United States: Franklin Hudson Publishing Co,


1905

Credits: Sonya Schermann and the Online Distributed Proofreading


Team at https://www.pgdp.net (This file was produced from
images generously made available by The Internet Archive)

*** START OF THE PROJECT GUTENBERG EBOOK OVER THE


SANTA FÉ TRAIL, 1857 ***
Transcriber’s Note
Larger versions of most illustrations may be seen by right-
clicking them and selecting an option to view them separately,
or by double-tapping and/or stretching them.
Additional notes will be found near the end of this ebook.
Over the Santa Fé Trail
1857

BY
W. B. NAPTON.
1905.
FRANKLIN HUDSON PUBLISHING CO.,
KANSAS CITY, MO.
CONTENTS
Page
I. Captain “Jim Crow” Chiles 3
II. In Camp, South of Westport 10
III. Buffalo 14
IV. Companions of Voyage 18
V. Pestiferous Indians 21
VI. At the Kiowa Camp 28
VII. To the Cimarron 33
VIII. My First Antelope 38
IX. A Kicking Gun and a Bucking Mule 46
X. A Gray Wolf 50
XI. Arrival at Las Vegas 54
XII. In Peril of Indians 62
XIII. Captain Chiles’ Chase 69

LEWIS & CLARK’S ROUTE RETRAVELED


Chapter I 73
Chapter II 84
Chapter III 93
ILLUSTRATIONS
Page
“Jim Crow” Chiles Laughed 7
The Mule Suddenly Bucked 24
Punched Him With the Point 26
Difficult to Get the Heavily Loaded Wagons Across 34
Their Drivers Were Unable to Restrain Them 40
“Skeesicks” Walked Up 44
He Plodded Along With the Lame Cattle 46
He Jumped and Kicked 48
The Officers Dragged Him Out 60
“Men, They Are Indians!” 66
Over the Santa Fé Trail, 1857.

I.
Captain “Jim Crow” Chiles.

When I was a lad of 12 years of age my father had a red-headed


overseer, good-natured, loquacious and fond of telling stories, the
kind that suited the understanding and tickled the fancy of a boy. His
stories were always related as being truthful accounts of actual
occurrences, although I suspected they were frequently creatures of
his own imagination. This overseer, a Westerner born and bred, had
driven an ox wagon in a train across the plains to New Mexico; had
made two trips across—in 1847 and 1848—one extending as far as
Chihuahua, in Old Mexico. His observation was keen, and his
memory unexcelled, so that, years afterwards, he could relate, in
minute detail, the events of every day’s travel, from the beginning to
the end of the journey. I was charmed with his accounts of the
Indians and buffalo, wolves, antelope and prairie dogs.
Reaching the age of 18 in 1857, with indifferent health, my father
acquiesced in my determination to cross the plains to New Mexico.
The doctor said the journey would benefit my health. Already an
expert with a gun or pistol, I had killed all kinds of game to be found
in Missouri, and had read Gordon Cumming’s book of his hunting
exploits in South Africa, so that I felt as if nothing less than killing big
game, like buffalo and elk, could gratify my sporting proclivities.
Colonel James Chiles of “Six Mile,” Jackson County, was a state
senator, and while at Jefferson City during the session of the
legislature, my father telling him of my desire to go out to Santa Fé,
the colonel sent me an invitation to come to his house by the middle
of April and go out with a train belonging to his son. So in the early
spring of 1857 I set out from my home in Saline County, well
mounted and equipped for the journey.
The spring was backward, and when I reached Colonel Chiles’s
house in the middle of April winter was still “lingering in the lap of
spring.” The grass was not good on the plains until the 10th of May.
It was arranged for me to go out with the train commanded by “Jim
Crow,” a son of Colonel Chiles.
“Jim Crow” was then about twenty-five, not over medium height,
but strong, athletic and wiry, and had a pretty well established
reputation as a fighter among the frontiersmen. He had killed a
lawyer named Moore, who lived at Leavenworth, in the Noland hotel
at Independence. After the Civil War he killed two other men at
Independence, and he himself was eventually killed in a fight with
the Independence town marshal. But I found “Jim Crow” a kind and
considerate friend, jovial and good natured generally, but subject to
violent fits of anger, and when angry, a very dangerous man. One
night on the “trail,” while he and I were riding some distance ahead
of the train, amid the solitude of the darkness and the vast plains, the
conversation drifted into a confidential vein. He recalled the killing of
Moore, saying he regretted it beyond measure; that the affair had
haunted him day and night; that he would willingly give up all that he
owned or expected to acquire to be relieved of the anguish and
trouble and remorse the act had caused him. But he was possessed
of the kind of courage and combativeness which never suggested
the avoidance of a fight then or afterward.
Kansas City was even then, in 1857, an aspiring town. For a
month or two in the spring the levee was covered with wagons and
teams, and sometimes four or five steamboats were at the wharf
discharging freight. General John W. Reid had recently bought forty
acres, the northwest corner of which is now the intersection of
Broadway and Twelfth street, for $2,000. The land was covered with
timber, which he cut into cord wood and sold to the steamboats for
about enough to pay for the land.
There were no streets, and only one road from the levee, leaving
the river front at Grand avenue, running obliquely across to Main
street and back again to Grand avenue, in McGee’s addition.
Colonel Milton McGee had taken down his fences and laid off his
cornfields into lots.
The work cattle and wagons were collected and a camp
established, about the first of May, on the high, rolling prairie near
the Santa Fé trail, three miles southwest of Westport. The wagons
were heavy, cumbrous affairs with long deep beds, covered with
sheets of heavy cotton cloth, supported by bows. A man six feet high
could stand erect in one of them, and they were designed to hold a
load of seven or eight thousand pounds of merchandise each. Those
in our train were made by Hiram Young, a free negro at
Independence, and they were considered as good as any except
those with iron axles. The freight consisted of merchandise for the
trade in New Mexico. Two of the wagons were loaded with imported
champagne for Colonel St. Vrain of Las Vegas and Mora.
There was a shortage of good ox drivers that spring and Captain
“Jim Crow” found it difficult to supply the number he needed. Twenty-
five dollars a month “and found” were the wages. One evening, while
we were lounging around the corral, waiting for supper, three men
came up on foot, inquiring for the captain of the train. They were
good looking, well dressed men, two of them wearing silk hats, but
bearing no resemblance to the ordinary ox driver. They said they
were stranded and looking for work. They proposed to Captain
Chiles to hire to him for drivers, while they disclaimed any knowledge
of the calling.
“JIM CROW” CHILES LAUGHED.

“Jim Crow” laughed, and after interrogating them as to their


antecedents, said he would hire them on probation. “I will take you
along,” he said, “and if I find you can learn to drive cattle before we
get to Council Grove, the last settlement on the road, then I’ll keep
you; otherwise not, and you must look out for yourselves.”
They were invited to supper and assigned to a mess. One of
them was named Whitcom. He hailed from Massachusetts and had
never seen a yoke of oxen in his life, but he was strong, sturdy and
active, and before we reached New Mexico he was rated the most
dextrous driver in the outfit. Moreover, his team looked better than
any in the train when we reached the end of our journey. Ten years
ago Whitcom was living in Cheyenne, and was one of the wealthiest
cattle raisers in the state of Wyoming.
Another of the three hailed from Cincinnati. He wore a
threadbare suit of broadcloth and a “plug” hat, and was tall, angular,
awkward, slip-shod and slouchy in appearance. He had been
employed in his father’s banking house in Cincinnati, and was
accomplished in penmanship and a good accountant; but he proved
to be utterly unfit for an ox driver. He could not hold his own among
his rough companions, and became the object of their jeers and
derision. By unanimous consent he was given the name of
“Skeesicks,” and by this name he was known ever afterwards.
The third of the trio proved to be a fairly good driver, and is now
a prosperous merchant in the state of Montana.
Among the drivers was a young Mexican, Juan, who had been in
the employ of the Chiles brothers for years. Through him we were
enabled to converse with the Kiowas and Comanches when we
reached them. Many of the Indians could speak or understand
Spanish, but could not understand a word of English. We had men
among the teamsters from Tennessee, Kentucky, Arkansas and
Texas. They soon became known and answered to the name of their
own state. “Tennessee” and “Texas” prided themselves on the size
and weight of their whips, and the loudness of the noise they could
make in popping them.
Young Reece, from Missouri, went out with the train for his
health. He had consumption and hoped the journey over the plains
would be of benefit to him. He was very tall, being six feet four
inches, of large bone and frame, but thin as a huge skeleton, and
had allowed his heavy black hair to grow until it hung below his
shoulders. He was well off so far as property was concerned, and
rode a splendid dapple gray horse, muscular, tough and graceful,
with handsome mane and tail, which could fairly fly over the prairie.
II.
In Camp, South of Westport.

In the camp, three miles southwest of Westport, we were


detained for a fortnight or more, awaiting the arrival of our freight at
Kansas City. There were twenty-six wagon, five yoke of oxen to
each, carrying about seven thousand pounds of freight each. There
were no tents, so we slept on the ground, either under a wagon or, if
we preferred it, the broad canopy of heaven.
Captain “Jim Crow” commanded the company, with Rice as
assistant wagonmaster. There was one driver for each wagon, and a
boy of 16, of frontier origin and training, whose duty it was to drive
the “cavayard” or loose cattle, taken along in case any of the teams
should get lame or unfit for service. “Jim Crow,” immediately on his
arrival at the camp, gave the boy the nickname of “Little Breeches,”
suggested by his very tight-fitting trousers, and the name,
abbreviated to “Little Breech,” stuck to him.
While encamped below Westport I was fortunate in purchasing a
first rate “buffalo horse,” a California “lass horse,” that had been
brought across the plains the previous year. He proved his
excellence afterward, was very fast and would run up so close to a
buffalo that I could sometimes touch him with the pistol point.
Camped in our vicinity were several corrals of trains belonging to
Mexican merchants, who used mules instead of oxen, and had lately
come up from New Mexico. These Mexicans subsisted altogether on
taos (unbolted) flour, and dried buffalo meat, while our mess wagon
was filled with side bacon, flour, coffee, sugar, beans and pickles.
I soon got on fair terms of acquaintance with the master of one
of these Spanish trains. He was a successful buffalo hunter, but I
was surprised to find he used a spear for killing them, instead of a
pistol. When a buffalo was found at a distance from the road or camp
he would goad the animal, until so enraged, it would turn upon and
follow him, and in this manner he would get the game to a more
convenient place for butchering, before finally dispatching it.
There were no farms fenced up in sight of our camp at that time,
but the prairie was dotted with the houses of the “squatter
sovereigns,” who were “holding down” claims.
On the 10th day of June we yoked up and started on the long
journey. At the outset everybody about the train, from the captain to
the cavayard driver, was filled with good humor. The weather was
perfect, the view of the apparently boundless prairie exhilarating.
The road having been surveyed and established by the government
before the country was at all occupied, was almost as straight as an
arrow toward the southwest. The wagonmaster would arouse the
men before daylight in the morning and the cattle would be driven up
to the corral, yoked up and hitched to the wagons by the time the
cooks could prepare breakfast, a cook being assigned to each mess
of six or eight men. Some of the oxen were not well broken to the
yoke, and it was a difficult task at the dim break of day for a green
man to select each steer that belonged to his team in the corral,
where the 250 were crowded together so that their sides would
almost touch.
Once on the road the drive was continued for from eight to
twelve miles, the stops being governed by the convenience of
camping-places, where grass and water could be found for the
cattle. Familiarity with the route was essential in the wagonmaster,
who, riding some distance ahead, would select the camping-place,
and when the train came up direct the formation of the corral. The
cattle were immediately unyoked and turned loose, herded by two of
the teamsters. Often it was necessary to drive the cattle a mile or
more from the corral in order to find sufficient grass, that near the
road being kept short by the incoming trains from Mexico and the
outgoing trains ahead of us.
At Council Grove there was a considerable settlement of Indian
traders. There we found assembled a large band of Kaw Indians,
who had just reached there from a buffalo hunt on the Arkansas. The
Kaws were not classed as “wild” Indians, and I think had been
assigned to a reservation not far off, but when they got off on a hunt
their native savage inclinations made them about as dangerous as
those roaming the plains at will, and whose contact with the white
man was much less frequent.
Beyond the Diamond spring we met two men on horseback, who
were hunting cattle belonging to a train then corralled some distance
ahead. The cattle had been stampeded by Indians in the night and
they had lost fifty head. The train could not be moved without them.
The men had been in search of them for two days and thought they
would be compelled to offer a reward for them, that being found
necessary sometimes, along the border. The Indians and
“squawmen”—white men married to, or living with, Indian squaws—
would stampede cattle at night, drive them off and hold them until
they ascertained that a reward had been offered for them. Then they
would visit the corral, learn with seeming regret of the cause of the
detention of the train, declare that they were well acquainted with the
surrounding country and could probably find them and bring them in,
offering to perform this service for so much a head. After the bargain
was struck the cattle would be delivered as soon as they could be
driven from the place of their secretion. It was not infrequent for a
band of Kaws to strike a wagon master in this way for as much as
from $100 to $500.
Here we learned that Colonel Albert Sidney Johnson, in
command of a considerable force, had moved out from Fort Scott
against the Cheyennes, who were on the warpath up on the
Republican river, in the western part of Kansas, but we missed
seeing the command until months later, on our homeward journey in
September.
III.
Buffalo.

As we were drawing near the buffalo range preparations were


made for a chase. The pistols were freshly loaded and butcher
knives sharpened. One morning about 9 o’clock, on Turkey creek, a
branch of the Cottonwood, we came in sight of buffalo, in a great
mass, stretching out over the prairie as far as the eye could reach,
though the topography of the country enabled us to see for several
miles in each direction. The prairie in front of us was gradually
undulating, but offered no great hindrance to fast riding. Reece and I
were anxious to try our skill, and Captain Chiles said he would go
along to assist in butchering and bringing up the meat; but, as he
was riding a mule, he could not be expected to take an active part in
the chase. Reece was mounted on his splendid iron gray and I on
my trained buffalo horse, each of us having a pair of Colt’s navy
revolvers, of six chambers in holsters.
We rode slowly until we got within three or four hundred yards of
the edge of the vast herd. Then they began to run and we followed,
gaining on them all the time. Pressing forward, at the full speed of
my horse, I discovered that the whole band just in front of me were
old bulls. I was so anxious to kill a buffalo that I began shooting at a
very large one, occasionally knocking tufts of hair off his coat, but
apparently having little other effect. However, after a lively run of
perhaps a mile or two he slackened his pace, and at last stopped still
and, turning about, faced me. I fired the one or two remaining
charges of my revolvers, at a distance of twenty or thirty yards, and
thought he gave evidence of being mortally wounded. After gazing
steadily at me for a few minutes he turned around and walked off. I
followed, but presently he resumed a gallop in the direction the main
herd had gone, soon disappearing from view over a ridge. So I had
made a failure, and felt a good deal put out, as well as worn out by
the fatigue of fast riding.
Through a vista between the clouds of dust raised by the buffalo,
I got a glimpse of Reece. His horse proved to be very much afraid of
the buffalo and could not be urged close enough to afford shooting,
with any degree of certainty, with a pistol. Reece held his magnificent
horse with a rein of the bridle in either hand, his head fronting
towards the buffalo, but the frightened animal would turn to one side,
despite the best efforts of his master, fairly flying around in front of
the herd. That was Reece’s first and last attempt to kill a buffalo on
horseback.
I rode back towards the train, soon meeting Captain Chiles, who
greeted me with derisive laughter, but considerately expressed the
hope that I would have better success upon a second attempt. As we
were all very anxious to get some fresh meat, he suggested that I
should lend him my horse; that he would easily kill one with a
double-barrel shotgun, which he was carrying in front on his saddle. I
readily agreed to this, and mounting on my horse, he put off and
promptly slew a fat, well-grown calf that proved good eating for us
who had lived on bacon for many days.
That afternoon I turned my buffalo horse loose, permitting him to
follow, or be driven along with the cavayard, in order that he might
recuperate from the exhausting races of the forenoon. The following
morning he was as good as ever, and I resolved to try another
chase.
Having received some pertinent instructions from Captain Chiles,
as to the modus operandi of killing buffalo on horseback at full
speed, I mounted and sallied forth with him, the weather being ideal
and the game abundant.
At the left of the road, in sight, thousands of buffalo were grazing
in a vast plain, lower than the ridge down which we were riding.
Opened up in our view was a scope of country to the southeast of
us, a distance of ten miles. This plain was covered with them, all
heading towards the northwest.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like