Hi everybody! In this tutorial, we are going to be building a really simple file-upload HTTP server that allows you to upload your files to the server running your Go application.
There are countless different reasons why you would want to do this, you could be uploading CSV reports for further processing within your complex financial system, or you could be creating a cool image manipulation app that allows you to modify various aspects of any photos you want to upload.
Thankfully, the task of dealing with image uploading in Go is fairly simple and, coupled with the new
TempFile API introduced in Go version 1.11, we can come up with a really elegant system fairly quickly!
Note - You can read more about the TempFile api in my other tutorial here: Go Temporary Files and Directories
We’ll start off by creating a really simple HTTP server using the
net/http package. This will feature just the one solitary endpoint which will be our
If we want to run this, we can do so by running
go run main.go and if we haven’t made any mistakes, we should see our server starting up successfully.
Ok, so now that we have a base to build on top of, let’s set about implementing our upload endpoint to handle file uploads.
Awesome, we can try running this and seeing if everything else works by again calling
go run main.go within our terminal.
We’ll need a really simple HTML frontend that will act as our portal for uploading our files. We won’t bother with any of the more complex aspects such as authentication and user management, we’ll just create a really simple
form element that will allow us to select a file from our local machine and hit the API endpoint we have defined above!
Awesome, we can now test that what we have done works and it successfully uploads our files!
Try opening up this
index.html file within your browser and try uploading a file to our running web server.
You should see that a new file has been generated in the
temp-images/ directory that follows the convention
Hopefully you found this tutorial useful and entertaining! If you did, or you spotted anything wrong with the tutorial, then please feel free to let me know through the suggestion section below!
Note - If you want to keep track of when new Go articles are posted to the site, then please feel free to follow me on twitter for all the latest news: @Elliot_F.