We use cookies and other tracking technologies to improve your browsing experience on our site, analyze site traffic, and understand where our audience is coming from. To find out more, please read our privacy policy.

By choosing 'I Accept', you consent to our use of cookies and other tracking technologies.

We use cookies and other tracking technologies to improve your browsing experience on our site, analyze site traffic, and understand where our audience is coming from. To find out more, please read our privacy policy.

By choosing 'I Accept', you consent to our use of cookies and other tracking technologies. Less

We use cookies and other tracking technologies... More

Login or register
to apply for this job!

Login or register to start contributing with an article!

Login or register
to see more jobs from this company!

Login or register
to boost this post!

Show some love to the author of this blog by giving their post some rocket fuel 🚀.

Login or register to search for your ideal job!

Login or register to start working on this issue!

Engineers who find a new job through Golang Works average a 15% increase in salary 🚀

Blog hero image

Go + Postgres + Heroku Tutorial

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 waseef blog 1.jpg

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 run heroku 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 binfolder, and the intermediary compiled objects in thepkgfolder. 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

4. Create the Hello World! Application

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.

5. Create the Heroku Application

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.

6. Create the ProcFile

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

7. GoDep

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

8. Commit Everything & Deploy!##

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

9. Add Postgres DB

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.

10. Connect to your DB

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.

11. Next Steps

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.

Thanks!

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.

Originally published on medium.com