Deployment
I am choosing to deploy our web application to Heroku for the sake of this
tutorial because in my experience it has been the fastest way to get a web
application up and running in no time. Remember that the focus of this tutorial
is how to build web applications in Go and not getting caught up in all
of the distraction of provisioning, configuring, deploying, and maintaining the
machines that our Go code will be run on.
If you don’t already have a Heroku account, sign up at
id.heroku.com/signup. It’s quick, easy and free.
Application management and configuration is done through the Heroku toolbelt,
which is a free command line tool maintained by Heroku. We will be using it to
create our application on Heroku. You can get it from
.
To make sure the application from our last chapter will work on Heroku, we will
need to make a few changes. Heroku gives us a environment variable
and expects our web application to bind to it. Let’s start by importing the
“os” package so we can grab that PORT
environment variable:
port := os.Getenv("PORT")
if port == "" {
Lastly, we want to bind to that port in our http.ListenAndServe
call:
http.ListenAndServe(":"+port, nil)
The final code should look like this:
We need a couple small configuration files to tell Heroku how it should run our
application. The first one is the Procfile
, which allows us to define which
processes should be run for our application. By default, Go will name the
executable after the containing directory of your main package. For instance,
if my web application lived in , myProcfile
will look like this:
web: deployment
Specifically to run Go applications, we need to also specify a .godir
file to
tell Heroku which dir is in fact our package directory.
deployment
Initialize the project as a Git repository:
Create your Heroku application (specifying the Go buildpack):
Push it to Heroku and watch your application be deployed!
git push heroku master
View your application in your browser: