SFTP is widely considered to be a standard and secure protocol through which parties can safely transfer files and data. However, the matter of actually engaging with an SFTP server can be quite troublesome, especially if you’re using the always under-documented Go. Which brings us to this post right here: By the end of the following tutorial, you will be able to utilize and connect to SFTP with your hands tied behind your back!
As always, preparation comes first. The libraries
golang.org/x/crypto/ are required in order to connect and interact with an SFTP server. When you are ready to install them, manually run:
$ go get github.com/pkg/sftp $ go get golang.org/x/crypto/ssh
Or create a go.mod file and declare your dependencies in it. Go.mod files define Go modules, which, amongst other things, is used to add dependencies to other Go modules. Save the following as go.mod:
Connecting to SFTP and Disconnecting
In this post, we’ll be using an environment variable named SFTPTOGO_URL that contains all the information required to connect to an SFTP server in a URI format: sftp://user:password@host. When you use SFTP To Go as an Heroku add-on, this variable is automatically created in your app and contains all required information. In the code below, the variable is parsed to extract the URI parts, and the remote server’s host key is fetched from the
known_hosts file to identify the remote host.
Once the connection is established, the SFTP client object will be assigned to the variable:
Now that we have set up a connection, we can use it to list files on the remote SFTP server. This is done by calling the
listFiles function, and passing both the SFTP client (
sc) and the remote directory path to the listfiles function as arguments. An example call would look like this:
listFiles(*sc, "."). The function prints out the name, modification timestamp, and size of the files in the SFTP server.
The next step is to upload a file. Use the
uploadFile function and pass the following arguments: the SFTP client, the path to the local file, and the remote path (which is where the file should end up after we upload). A function call would look like this:
uploadFile(*sc, "./local.txt", "./remote.txt")
We’re almost done! We just need to download our files. Use the
downloadFile function, and pass the SFTP client, the path to the remote file, and the local path in which to store the downloaded file to the function. You would call the function like this:
downloadFile(*sc, "./remote.txt", "./download.txt")
The Whole Thing
So we’ve made it to the end! If you would like to run the entire program from start to finish, copy the following code and save it as
Finally, run it using the command:
All done! Congratulations on connecting to SFTP using Go!
Check out more code samples on Github.