Waseef Shawkat
21 May 2019
•
3 min read
A quick Hello World! guide on setting up a RESTful API written in Golang, hosted on Heroku and connected to a Postgres database
1. Create a Heroku Account
It is free and does not require you to enter your credit card: Link.
2. Download and Install the Heroku CLI
Instructions on how to do this is here: Link. You can verify it was successfully installed by running
heroku --version
in your terminal. Once that is done runheroku login
to sign in to the Heroku account that was just created.3. Install Go
Instructions on how do this is here: Link. Likewise, once that is done you can verify it was successfully installed by running
go version
.
A critical part of setting up a RESTful API in Go is understanding Go’s folder structure. All Go code is organized into a workspace rooted around the $GOPATH
. The $GOPATH
is the parent folder in which all Go code is to be kept. Typically the $GOPATH
is set to $HOME/go
. $HOME
is the root directory for all user applications on Unix systems. The workspace will contain the source code for multiple Go packages in the src
folder. The compiled binaries in the bin
folder, and the intermediary compiled objects in thepkg
folder. The Go tooling expects your code to be organized like this. Set up your folder structure similar to the one below.
$HOME/go - workspace root
/src - source code
/bin - compiled binaries
/pkg - intermediaries
Make sure to add the $GOPATH
to the bash profile.
export GOPATH=$HOME/go
export PATH=$GOPATH/bin:$PATH
Create a folder under the src
folder named helloworld
.
mkdir -p $GOPATH/src/helloworld
Inside the helloworld
folder create main.go
and copy paste the below code.
package main
import (
"log"
"fmt"
"net/http"
"os"
)
func main() {
// get the port
port, err := getPort()
if err != nil {
log.Fatal(err)
}
// GET /
http.HandleFunc("/", hello)
// start the server
log.Printf("Listening on %s...\n", port)
if err := http.ListenAndServe(port, nil); err != nil {
panic(err)
}
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello World!")
}
func getPort() (string, error) {
// the PORT is supplied by Heroku
port := os.Getenv("PORT")
if port == "" {
return "", fmt.Errorf("$PORT not set")
}
return ":" + port, nil
}
The above code is pretty self explanatory. The starting point of the application is the main
function. We get the port which is supplied on application startup. We have one GET
endpoint on /
which simply outputs Hello World!. Finally we start the server on the specified port.
To build the binary file run the following command
go install
Then you can run the application with the following command
PORT=8000 $GOPATH/bin/helloworld
You can then visit localhost:8000 on your browser and you should see the text Hello World! on the screen.
From the command line simply run. This will create a Heroku app for you with a random name and will show you the URL.
heroku create
When you create an app, a git remote (called heroku
) is also created and associated with your local git repository.
Heroku uses a file name Procfile
to determine what to run. Create a file named Procfile (no extensions). In the first line put
web: helloworld
Go dependencies are managed using a tool called GoDep. To install it run
go get -u github.com/tools/godep
Once that is installed run the following command
godep save
This will create a Godep.json
file which stores all your dependencies
Commit all the changes that you made to your local repository. Once that is done run
git push heroku master
This will trigger the deploy process and your application should now be deployed.
You can run the command below to see if your application is running.
heroku open
You can also tail the logs using the command below
heroku logs --tail
To add a Postgres DB you first need to configure the add-on in your Heroku control panel. Login to heroku.com
and navigate to the created application’s dashboard. You should see tabs such as overview, resources, deploy, metrics
. Click on the resources
tab. In the search bar search for Heroku-Postgres
. A pop-up should open up when you select the resource and choose the plan you want. hobby-dev
is free up to 10,000
rows at the time of writing. Click Provision and you now have an instance of a Postgres DB for your application.
Heroku supplies the DB url in your app as an environment variable, DATABASE_URL
.
To connect to it copy-paste the following code snippet:
// retrieve the url
dbURL := os.Getenv("DATABASE_URL")
// connect to the db
db, err := sql.Open("postgres", connStr)
You should now be connected to your Postgres instance running on Heroku.
There are still several steps that you can take to create a production ready server. To setup your local environment you will most likely need to install Postgres locally. Along with that, you also most probably some other frameworks and tools to help you. I have personally used refresh, chi and upper db at work.
Hopefully you found this article useful. There are several other articles out there that show the same process, but I tried breaking it down as much I could.
Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ
108 E 16th Street, New York, NY 10003
Join over 111,000 others and get access to exclusive content, job opportunities and more!