This project is a staff and contract management system with APIs only. It provides functionalities for two user roles: Admin and Staff. Admin can manage all staff and their contracts, while staff can only manage their own contracts. All APIs require JWT token authentication.
-
Install Dependencies Make sure you have Go installed. Then, run:
go mod tidy
-
Run the Application
go run cmd/main.go
- Login
- POST
/auth/login
- Input:
{ "username": "string", "password": "string" }
- Output:
{ "token": "string" }
- POST
-
Create Contract
- POST
/contracts/
- Input:
{ "Title": "string", "Content": "string" }
- Output:
Contract Object
- POST
-
Get Contracts
- GET
/contracts/
- Output:
List of Contract Objects
- GET
-
Get Contract Detail
- GET
/contracts/:id
- Output:
Contract Object
- GET
-
Update Contract
- PUT
/contracts/:id
- Input:
{ "Title": "string", "Content": "string" }
- Output:
Updated Contract Object
- PUT
-
Delete Contract
- DELETE
/contracts/:id
- DELETE
-
Create Staff
- POST
/staffs/
- Input:
{ "Username": "string", "Password": "string", "Role": "string" }
- Output:
Staff Object
- POST
-
Get Staffs
- GET
/staffs/
- Output:
List of Staff Objects
- GET
-
Get Staff Detail
- GET
/staffs/:id
- Output:
Staff Object
- GET
-
Update Staff
- PUT
/staffs/:id
- Input:
{ "Username": "string", "Password": "string", "Role": "string" }
- Output:
Updated Staff Object
- PUT
-
Delete Staff
- DELETE
/staffs/:id
- DELETE
To run the tests, navigate to the tests/scripts
directory and run the test script:
cd tests/scripts
go run run_tests.go
This will run all the unit tests and output the results.
Background tasks are handled using NATS. The delete.contract
and delete.staff
subjects are used to process delete tasks in the background.
-
Initialize NATS
nc := utils.InitNATS()
-
Subscribe to Delete Tasks
go tasks.SubscribeToDeleteTasks(nc, db)
-
Publish to NATS for Background Task
nc.Publish("delete.contract", []byte(contractID)) nc.Publish("delete.staff", []byte(staffID))
utils/db.go
func InitDB() *gorm.DB {
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
log.Fatal("Failed to connect database")
}
db.AutoMigrate(&models.Staff{}, &models.Contract{})
return db
}
utils/nats.go
func InitNATS() *nats.Conn {
nc, err := nats.Connect(nats.DefaultURL)
if err != nil {
log.Fatal(err)
}
return nc
}
utils/respond.go
func RespondError(w http.ResponseWriter, code int, message string) {
RespondJSON(w, code, map[string]string{"error": message})
}
func RespondJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}