I'm implementing a system where I have two structs one for a User and another one for the Worker
>! The user section
type User struct {
Email string `json:"email"`
Name string `json:"name"`
Password string `json:"password"`
}
type Users struct {
Users []User `json:"users"`
}
>! The worker section
type Worker struct {
Email string `json:"email"`
Name string `json:"name"`
Password string `json:"password"`
}
type Workers struct {
Workers []Worker `json:"workers"`
}
Both the structs are stored in two different files according to their function: user.go and worker.go. Here's a sample code for the user.go file basically calling the readUser() function from the jsonhandler.go file.
// Check if the user already exist or not
func check(email string) (bool, User) {
users := readUser()
for i := 0; i < len(users.Users); i++ {
if email == users.Users[i].Email {
return true, users.Users[i]
}
}
return false, User{}
}
func UserSignIn(c *fiber.Ctx) error {
// Function to add a new user to the database and check if it already exists
// send en error if there is a problem while parsing the JSON data
user := new(User)
if err := c.BodyParser(&user); err != nil {
return errorResponse(c, err)
}
// Check if the user is available and send the response accordingly
if isAvilable, _ := check(user.Email); isAvilable {
response200(c, "user already exist")
} else {
return response200(c, "user doesn't exist")
}
return nil
}
I have created the same functions for handling the worker struct (for example checkWorker() and WorkerSignIn()) basically doing the same thing. But, I also had to create another function readWorker() to read values for the worker struct. In the jsonhandler.go file I have created a function to read data from the JSON file.
func readUser() Users {
var users Users
file, _ := os.Open("user.json")
defer file.Close()
byteValue, _ := io.ReadAll(file)
json.Unmarshal(byteValue, &users)
return users
}
But it cannot read data from the worker.json file from the same function so I had to create another function readWorker() basically doing the same thing.
I tried to create a common function that returns an interface{} type but I cannot access the values, for example I was getting errors in operations like:
for i := 0; i < len(users.Users); i++ {
if email == users.Users[i].Email {
return true, users.Users[i]
}
}
I'm getting error while accessing the Email and users.Users fields.
You can use type assertion to convert interface{} to your struct type. this is an example