Task-2 @Catseye Systems, Create a CRUD application with Go using Gin & PostgreSQL

Author Image

Kaustubh Patil

October 14, 2024 (6mo ago)

Building a RESTful CRUD API in Go with Gin and PostgreSQL

If you're interested in creating a backend API in Go, this guide shares my experience setting up the environment, installing PostgreSQL, and using the Gin framework to handle CRUD operations. While I’m still learning, I found that with Go's speed and the simplicity of Gin, it’s possible to have a functional API up and running relatively quickly.

Why Go for APIs?

Go is designed for high performance and simplicity, making it an ideal language for backend services. Combined with the Gin framework, which is both fast and minimalist, you get a clean and efficient environment for developing APIs. PostgreSQL, meanwhile, is a powerful and versatile database that pairs well with Go, especially when dealing with relational data.


Setting Up the Environment

Step 1: Setting Up Go

First, install Go and configure the environment. This involves setting your $GOPATH, $GOBIN, and adding them to your $PATH. Once this is done, create a new project directory for your CRUD API.

Step 2: Initialize a Go Module

Navigate to your project directory and initialize a new Go module using go mod init. This will create a go.mod file where all your dependencies are tracked.


Installing PostgreSQL

With your Go environment ready, the next step is to install PostgreSQL. PostgreSQL offers robust data handling and integrates smoothly with Go using the pq library for SQL database management. After installation, create a database and a sample table to store our data.


Building the CRUD API

Step 1: Installing Dependencies

We’ll use two main packages for this project: Gin, for handling HTTP requests, and pq, a PostgreSQL driver for Go. With these installed, our project structure will start taking shape.

Step 2: Setting Up the Project Structure

  1. Database Configuration: In main.go, set up a database connection to PostgreSQL. Create a reusable function to establish the connection, so our handlers can query data with ease.
  2. Defining the Item Model: Define a simple model for an Item, which includes an ID and a Name.
  3. Creating Handlers: Define handlers for each CRUD operation:
    • Create: Accepts POST requests to add a new item.
    • Read: Fetches all items or a specific item by ID.
    • Update: Updates the details of an item.
    • Delete: Deletes an item by ID.
  4. Setting Up Routes: Use Gin to route requests to the appropriate handler functions.

Step 3: Testing the Endpoints

With the project structure in place, you can test each endpoint to ensure everything works correctly. Using a tool like Postman makes it easy to send requests and verify responses.


Commands for Setup

Step 1: Install Dependencies

echo "Installing Go packages..."

    go install github.com/gin-gonic/gin@latest
    go install github.com/lib/pq@latest
    echo "Dependencies installed."

Step 2: Set Up PostgreSQL Database

echo "Setting up PostgreSQL database..."

    DB_NAME="go_crud_db"
    DB_USER="postgres"
    DB_PASSWORD="<YOUR_PASSWORD>"

Instructions

Replace <YOUR_PASSWORD> with your actual PostgreSQL password in the script.

Create the database

psql -U "$DB_USER" -c

    "CREATE DATABASE $DB_NAME;"

Create the items table

psql -U "$DB_USER" -d "$DB_NAME" -c "

    CREATE TABLE IF NOT EXISTS items (
        id SERIAL PRIMARY KEY,
        name VARCHAR(100) NOT NULL
    );"

echo "Database and table created."

Step 3: Configure the connection string in main.go

    CONN_STR="postgres://$DB_USER:$DB_PASSWORD@localhost/$DB_NAME?sslmode=disable"
    sed -i "s|connStr := .*|connStr := \"$CONN_STR\"|" main.go
    echo "Connection string configured in main.go."

Step 4: Run the application

echo "Starting the Go application..."

go run main.go

Testing the API using Postman

  1. POST /items - Create an Item To create an item, use the following command:

    curl -X POST http://localhost:8080/items -H "Content-Type: application/json" -d '{"name": "Item1"}'
    
  2. GET /items - Get All Items To fetch all items, use:

    curl -X GET http://localhost:8080/items
    
  3. GET /items/:id - Get a Specific Item To get a single item by ID, use:

    curl -X GET http://localhost:8080/items/1
    
  4. PUT /items/:id - Update an Item To update an existing item by ID, use:

    curl -X PUT http://localhost:8080/items/1 -H "Content-Type:     application/json" -d '{"name": "Updated Item"}' 
    
  5. DELETE /items/:id - Delete an Item To delete an item by ID, use:

    {
    "message": "Item deleted"
    }
    

Conclusion

Using Go with Gin and PostgreSQL offers a powerful combination for building REST APIs. Go's simplicity, paired with the speed of Gin and the robustness of PostgreSQL, provides a highly efficient and scalable setup for any backend application. Now that the environment is ready, feel free to add authentication, further routes, or expand on the model to suit your needs!