An example template to make life easier when creating a simple Go web app
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.

Title: Leveraging Gorilla Mux for a Webserver with Postgres Date: 2018-02-26 19:19 Tags: go, golang, web, gorilla mux, postgres, pg, psql, http, httptest


# install docker in order to trivially run postgres locally
go get
sudo ./
sudo ./
sudo ./

Running it

./ (which just executes something like go run main.go db.go note.go)

Manually checking the web server

curl localhost:8080
    <html><body>index web page</body></html>

curl -I -X GET localhost:8080

HTTP/1.1 200 OK
Date: Sun, 15 Apr 2018 17:48:47 GMT
Content-Length: 40
Content-Type: text/html; charset=utf-8

curl -X POST --header "Content-Type: application/json" --data '{"note":"some note text"}' localhost:8080/note

Manually checking the database

sudo ./

Basic Testing

Unit testing should not require external dependencies, the -short command can still skip "long" unit tests

go test or go test -v

Integration Testing

Since the integration tests expect to actively use a real database there is an environment variable that tells the system how to initialize

Otherwise the integration tests are skipped, no database needed!

./ (or expandeded into TEST_INTEGRATION=true go test -v)

Environment variables (for overrides) and the default:

"TEST_DB_PORT", "5432"
"TEST_DB_SSL", "disable"
"TEST_DB_USERNAME", "myuser"
"TEST_DB_PASSWORD", "mypassword"
"TEST_DB_NAME", "mydb"

Code Structure

The application has different parts in order to separate concerns: and are helpers to setup a local dev environment using docker

  1. tables.sql is the database schema
  2. main.go initializes and starts the application
  3. db.go abstracts the persistence layer connection
  4. notes.go represents an example "model" (like MVC or
  5. router.go manage the routes to the web application
  6. controller-.go are the definitions of handlers for each route
  7. _test.go are test files