Downloading the Contents of the Phone Book Application

Let’s learn how to provide the contents of the phone book as a downloadable file.

We'll cover the following

In this lesson, we’ll create and implement an endpoint that allows us to download the contents of a single file. The code creates a temporary file with a different file name for each request with the contents of the phone book application. For reasons of simplicity, the presented code supports two HTTP endpoints: one for the default router and the other for the serving of the file. Because we are serving a single file, we are going to use http.ServeFile(), which replies to a request with the contents of the specified file or directory.

Coding example

Each temporary file is kept in the file system for 30 seconds before it is deleted. To simulate a real-world situation, the presented utility reads data.csv, puts it into a slice, and creates a file based on the contents of data.csv. The name of the utility is getEntries.go—its most important code is the implementation of the getFileHandler() function:

Get hands-on with 1400+ tech skills courses.