GORM
GORM Example
This is a sample program demonstrating how to use GORM as an ORM to connect to a SQLite database with the Fiber web framework.
Prerequisites
- Go 1.27 or higher
- Go modules
Setup
Clone the repository:
git clone https://github.com/gofiber/recipes.git cd recipes/gormInstall dependencies:
go mod tidy
Running the Application
Run the application:
go run main.goThe server will start on
http://localhost:3000.
Endpoints
| Method | URL | Description |
|---|---|---|
| GET | /api/v1/book | Retrieves all books |
| GET | /api/v1/book/:id | Retrieves a book by ID |
| POST | /api/v1/book | Creates a new book |
| DELETE | /api/v1/book/:id | Deletes a book |
Example Requests
Get All Books
curl -X GET http://localhost:3000/api/v1/bookGet Book by ID
curl -X GET http://localhost:3000/api/v1/book/1Create a New Book
curl -X POST http://localhost:3000/api/v1/book -d '{"title": "New Book", "author": "Author Name"}' -H "Content-Type: application/json"Delete a Book
curl -X DELETE http://localhost:3000/api/v1/book/1Using MySQL or PostgreSQL
SQLite keeps this recipe runnable without a database server, but GORM talks to every database through the same API. Only the driver and the connection string change. Install the driver you need:
go get gorm.io/driver/mysql
go get gorm.io/driver/postgresThen replace the gorm.Open call in initDatabase in main.go.
MySQL
import "gorm.io/driver/mysql"
// parseTime=True is required for time.Time fields and charset=utf8mb4 for full UTF-8 support.
// See https://github.com/go-sql-driver/mysql#dsn-data-source-name for the DSN format.
dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
database.DBConn, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})PostgreSQL
import "gorm.io/driver/postgres"
dsn := "host=localhost user=postgres password='' dbname=go-db port=5432 sslmode=disable"
database.DBConn, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})In both cases, create the database first (for example createdb go-db for PostgreSQL). To keep credentials out of the source, read the connection string from the environment, for example dsn := os.Getenv("DB_DSN"). AutoMigrate then creates the books table on startup, as it does for SQLite.