This is a template example for a CRUD appication (REST API) in Go with Postgres as a database authored by ojas.
Following is the API spec of the application:
API | Method | Description |
---|---|---|
/api/user/{id} | GET | Get a user given an uuid |
/api/users | GET | Get all users |
/api/newuser | PUT | Create a new user given the details |
/api/user/{id} | UPDATE | Update a user given an uuid |
/api/user/{id} | DELETE | Delete a user given an uuid |
The following go third-party packages are used:
- Gorilla Mux - Go router for incoming HTTP requests.
- Google UUID - Google's well maintained UUID golang package.
- Godotenv - Pakcage to load local environment files.
- Postgres Golang Driver - Go driver for Postgres. Check here for a full list of drivers.
The Postgres database contains a single table called users
:
type User struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Age int64 `json:"age"`
}
Any testing is done through Curl. A sample test for creating a new user is as follows API handler:
curl localhost:8080/api/newuser -d '{"id":"0a99e24d-ae00-49a9-8faa-c6c07ee70384","name":"mickey","age":50}' -X POST
Response:
{"id":"0a99e24d-ae00-49a9-8faa-c6c07ee70384","message":"User inserted successfully!"}
The following table is the commit-by-commit explanation of the development:
Commit | Message |
---|---|
commit 1 | Ping! |
commit 2 | chore: add file structure/intialize router |
commit 3 | feat: add users model and GetUsers API |
commit 4 | feat: add getAllUsers API |
commit 5 | feat: add newuser API to create a user |
commit 6 | feat: add UpdateUsers API |
commit 7 | feat: add DeleteUsers API |
commit 8 | chore: update documentation |