yumaojun03 a129d8b476 ```
feat(userapp): 添加用户管理应用的基础架构

- 新增DAO层实现数据访问对象模式,包含用户数据存储功能
- 集成Gin Web框架处理HTTP请求
- 实现用户创建和查询的API处理器
- 添加数据验证工具函数
- 配置项目依赖和模块管理
```
2026-03-01 12:05:06 +08:00

56 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)
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,
})
// {"message": "用户获取成功", "users": [{"Age": 25, "Email": "zhangsan@example.com", "ID": 1, "Name": "张三"}]}
}