| This repo is for go gin api .
-
Create Database
psql -U postgres # open psql CLI with user postgres CREATE DATABASE go-gin-api; \l # list all databases \q #CLI exit
-
Clone the project
git clone https://github.com/PolunLin/go-gin-api.git cd go-gin-api code . go mod init github.com/YOUR_USERNAME/go-gin-api
-
Install Modules
go get github.com/spf13/viper go get github.com/gin-gonic/gin go get gorm.io/gorm go get gorm.io/driver/postgres
-
Environment Variable
in
common/envs/.env
PORT=:3000 DB_URL=postgres://DB_USER:DB_PASSWORD@DB_HOST:DB_PORT/go-gin-api
tree /f
go-gin-api
│ go.mod
│ go.sum
│ Makefile
│ README.MD
│
├─cmd
│ main.go
│
└─pkg
├─books
│ add_book.go
│ controller.go
│ delete_book.go
│ get_book.go
│ get_books.go
│ update_book.go
│
└─common
├─config
│ config.go
│
├─db
│ db.go
│
├─envs
│ .env
│
└─models
book.go
make server # or
go run cmd/main.go
- POST:add a new Book
curl --request POST \ --url http://localhost:3000/books/ \ --header 'Content-Type: application/json' \ --data '{ "title": "Book A", "author": "Author", "description": "Some cool description" }'
- GET: Get All Books
curl --request GET --url http://localhost:3000/books/
- GET: Get Book by ID
curl --request GET --url http://localhost:3000/books/1/
- PUT: Update Book by ID
curl --request PUT \ --url http://localhost:3000/books/1/ \ --header 'Content-Type: application/json' \ --data '{ "title": "Updated Book Name", "author": "Another author", "description": "Updated description" }'
- DELETE: Delete Book by ID
curl --request DELETE --url http://localhost:3000/books/1/