Skip to main content

GORM MySQL Example

Github StackBlitz

This is a sample program demonstrating how to use GORM as an ORM to connect to a MySQL database with the Fiber web framework.

Prerequisites

  • Go 1.16 or higher
  • MySQL database
  • Go modules

Setup

  1. Clone the repository:

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

    go mod tidy
  3. Configure the database connection in the config.json file:

    {
    "DB_Username": "your_db_username",
    "DB_Password": "your_db_password",
    "DB_Name": "your_db_name",
    "DB_Host": "localhost",
    "DB_Port": "3306"
    }

Running the Application

  1. Run the application:

    go run main.go
  2. The server will start on 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/bookUpdates an existing book
DELETE/bookDeletes 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 -d '{"id": 1, "title": "Updated Book", "author": "Updated Author"}' -H "Content-Type: application/json"

Delete a Book

curl -X DELETE http://localhost:3000/book -d '{"id": 1}' -H "Content-Type: application/json"