我正在实现一个系统,其中有两个结构,一个用于 User,另一个用于 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"`
}
这两个结构体根据其功能存储在两个不同的文件中:
user.go
和worker.go
。这是 user.go
文件的示例代码,基本上从 readUser()
文件调用 jsonhandler.go
函数。
// 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
}
我创建了相同的函数来处理工人结构(例如
checkWorker()
和WorkerSignIn()
)基本上做同样的事情。但是,我还必须创建另一个函数 readWorker()
来读取 worker 结构的值。在 jsonhandler.go
文件中,我创建了一个函数来从 JSON 文件读取数据。
func readUser() Users {
var users Users
file, _ := os.Open("user.json")
defer file.Close()
byteValue, _ := io.ReadAll(file)
json.Unmarshal(byteValue, &users)
return users
}
但它无法从同一函数的
worker.json
文件中读取数据,因此我必须创建另一个函数 readWorker()
基本上做同样的事情。
我尝试创建一个返回
interface{}
类型的通用函数,但我无法访问这些值,例如我在以下操作中遇到错误:
for i := 0; i < len(users.Users); i++ {
if email == users.Users[i].Email {
return true, users.Users[i]
}
}
我在访问
Email
和 users.Users
字段时遇到错误。
您可以使用类型断言将 interface{} 转换为您的结构类型。 这是一个例子
user := readUsers().(*types.Users)