Unlock the Power of PostgreSQL with Go: Building a To-Do App

Why PostgreSQL?

PostgreSQL is a powerful, open-source object-relational database system with over thirty years of active development, earning it a strong reputation for reliability, feature robustness, and performance.

Getting Started

Before we dive into the project, make sure you have the following prerequisites set up:

  • Go: Install Go in your local environment as our programming language of choice.
  • PostgreSQL: Install PostgreSQL for development purposes, and consider a cloud offering like AWS Aurora for production.
  • pgAdmin 4: Download pgAdmin to visually manage your Postgres database.

Our Project: A Simple To-Do App

We’ll build a full-stack web application that performs CRUD operations on our Postgres database. Our to-do app will allow users to get, add, edit, and delete to-do items.

Setting Up the Server

Create a file named server.go in your project folder and add the following code:

package main

import (
    "log"
    "os"

    "github.com/gofiber/fiber/v2"
)

func main() {
    app := fiber.New()

    //...
}

Adding Routes

Let’s add four methods to handle GET, POST, PUT, and DELETE operations for our app:

app.Get("/", getIndex)
app.Post("/add", postHandler)
app.Put("/edit", putHandler)
app.Delete("/delete", deleteHandler)

Defining Handlers

We’ll define these methods to handle database interactions:

func getIndex(c *fiber.Ctx) error {
    //...
}

func postHandler(c *fiber.Ctx) error {
    //...
}

func putHandler(c *fiber.Ctx) error {
    //...
}

func deleteHandler(c *fiber.Ctx) error {
    //...
}

Connecting to the Database

Let’s create a connection to our database:

import (
    "database/sql"
    _ "github.com/lib/pq"
)

func main() {
    //...
    db, err := sql.Open("postgres", "user:password@localhost/database")
    if err!= nil {
        log.Fatal(err)
    }
    defer db.Close()
}

Fleshing Out Handlers

We’ll update our handlers to accept a pointer to our database connection:

func getIndex(c *fiber.Ctx, db *sql.DB) error {
    //...
}

func postHandler(c *fiber.Ctx, db *sql.DB) error {
    //...
}

func putHandler(c *fiber.Ctx, db *sql.DB) error {
    //...
}

func deleteHandler(c *fiber.Ctx, db *sql.DB) error {
    //...
}

Configuring Views

We’ll configure our Fiber app to serve HTML views:

app.Settings.Views.Layout = "./views"

Create a folder called views and add an index.html file:

<!DOCTYPE html>
<html>
<head>
    <title>To-Do App</title>
</head>
<body>
    <h1>To-Do App</h1>
    <ul>
        {{ range.todos }}
            <li>{{. }}</li>
        {{ end }}
    </ul>
</body>
</html>

Adding Styles

Create a style.css file in the public folder:

body {
    background-color: #f2f2f2;
}

ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

li {
    padding: 10px;
    border-bottom: 1px solid #ccc;
}

Starting the App

Run the app with go run main.go and visit http://localhost:3000 to see the to-do app in action!

Leave a Reply