Skip to main content

GORM with PostgreSQL Example

Github StackBlitz

This project demonstrates how to set up a Go application using the Fiber framework with GORM and PostgreSQL.

Prerequisites

Ensure you have the following installed:

  • Golang
  • Fiber package
  • GORM package
  • PostgreSQL

Setup

  1. Clone the repository:

    git clone https://github.com/gofiber/recipes.git
    cd recipes/gorm-postgres
  2. Install dependencies:

    go mod tidy
  3. Set up PostgreSQL and create a database:

    createdb go-db
  4. Configure the database connection via the DB_DSN environment variable:

    export DB_DSN="host=localhost user=postgres password='' dbname=go-db port=5432 sslmode=disable"

    If DB_DSN is not set, the application falls back to the default DSN above.

Running the Application

  1. Start the application:

    go run main.go
  2. Access the application at http://localhost:3000.

Endpoints

MethodURLDescription
GET/helloReturns a hello message
GET/allbooksRetrieves all books
GET/book/:idRetrieves a book by ID
POST/bookCreates a new book
PUT/book/:idUpdates an existing book
DELETE/book/:idDeletes a book

Example Requests

Get All Books

curl -X GET http://localhost:3000/allbooks

Get Book by ID

curl -X GET http://localhost:3000/book/1

Create a New Book

curl -X POST http://localhost:3000/book \
-d '{"title": "New Book", "author": "Author Name"}' \
-H "Content-Type: application/json"

Update a Book

curl -X PUT http://localhost:3000/book/1 \
-d '{"title": "Updated Book", "author": "Updated Author"}' \
-H "Content-Type: application/json"

Delete a Book

curl -X DELETE http://localhost:3000/book/1

References