59 lines
1.6 KiB
Go
59 lines
1.6 KiB
Go
package handlers
|
||
|
||
// https://github.com/gin-gonic/gin
|
||
// go mod tidy
|
||
import (
|
||
"fmt"
|
||
"os"
|
||
"userapp/dao"
|
||
"userapp/models"
|
||
"userapp/utils"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
// Gin 框架 对处理函数的要求:
|
||
// HandlerFunc defines the handler used by gin middleware as return value.
|
||
// type HandlerFunc func(*Context)
|
||
|
||
// c *gin.Context 是 Gin 框架传递给处理函数的上下文对象,包含了请求和响应的信息,可以用来获取请求参数、设置响应数据等
|
||
// 包含 用户请求(req), 通过是封装了一些常用的响应方法c.JSON(), 返回JSON格式的响应数据,设置响应头、状态码等
|
||
func CreateUser(c *gin.Context) {
|
||
// 创建用户
|
||
user := models.NewUser("张三", "zhangsan@example.com", 25, "password123")
|
||
user.ID = 1
|
||
|
||
if ok := utils.ValidateEmail(user.Email); !ok {
|
||
fmt.Println("邮箱格式错误")
|
||
os.Exit(1)
|
||
}
|
||
|
||
if ok := utils.ValidateAge(user.Age); !ok {
|
||
fmt.Println("年龄格式错误")
|
||
os.Exit(1)
|
||
}
|
||
fmt.Printf("用户创建成功:%+v\n", user)
|
||
|
||
// 返回用户信息
|
||
c.JSON(200, gin.H{
|
||
"message": "用户创建成功",
|
||
"user": user,
|
||
})
|
||
// {"message": "用户创建成功", "user": {"Age": 25, "Email": "zhangsan@example.com", "ID": 1, "Name": "张三"}
|
||
}
|
||
|
||
func GetUsers(c *gin.Context) {
|
||
users := dao.GetAllUsers()
|
||
|
||
// 返回用户信息
|
||
c.JSON(200, gin.H{
|
||
"message": "用户获取成功",
|
||
"users": users,
|
||
})
|
||
|
||
if len(users) > 0 {
|
||
fmt.Printf("第一个用户的密码哈希:%s\n", users[0].GetPasswordHash())
|
||
}
|
||
// {"message": "用户获取成功", "users": [{"Age": 25, "Email": "zhangsan@example.com", "ID": 1, "Name": "张三"}]}
|
||
}
|