GORM MySQL Example
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.25 or higher
- MySQL database
- Go modules
Setup
-
Clone the repository:
git clone https://github.com/gofiber/recipes.gitcd recipes/gorm-mysql -
Install dependencies:
go mod tidy -
Configure the database connection via the
DB_DSNenvironment variable:export DB_DSN="user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"If
DB_DSNis not set, the application falls back to the default DSN above.
Running the Application
-
Run the application:
go run app.go -
The server will start on
http://localhost:3000.
Endpoints
| Method | URL | Description |
|---|---|---|
| GET | /hello | Returns a hello message |
| GET | /allbooks | Retrieves all books |
| GET | /book/:id | Retrieves a book by ID |
| POST | /book | Creates a new book |
| PUT | /book/:id | Updates an existing book |
| DELETE | /book/:id | Deletes 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