参考文档:

项目结构

需要实现的功能

实现一个图书管理系统

  1. 用户服务:(登录,注册)、token验证
  2. 书籍操作:(对书籍的增删改查操作)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
├── controller // CLD:服务入口,负责处理路由,参数校验,请求转发
│   ├── book.go
│   └── user.go
├── dao // CLD:负责数据与存储相关功能(MySQL,Redis,ES等),以及业务的增删改查
│   ├── book.go
│   ├── mysql_init.go
│   └── user.go
├── go.mod
├── go.sum
├── main.go
├── middleware //中间件定义
│   └── auth.go
├── model // 模型定义
│   ├── book.go
│   └── user.go
└── router // 路由中间件注册
└── router.go

创建数据库

1
create database books charset utf8mb4;

实现过程

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//注册
fei@feideMacBook-Pro ~ % curl --location 'http://127.0.0.1:8000/register' \
--header 'Content-Type: application/json' \
--data '{
"username":"maxbit",
"password":"1234567"
}'
{"code":"90200","data":"maxbit 注册成功,请牢记您的密码","msg":"注册成功"}

//登陆
fei@feideMacBook-Pro ~ % curl --location 'http://127.0.0.1:8000/login' \
--header 'Content-Type: application/json' \
--data '{
"username":"maxbit",
"password":"1234567"
}'
{"msg":"登陆成功","token":"acc096ff-b82f-4836-a851-b6ca43ece8b8"}

//获取书籍列表
fei@feideMacBook-Pro ~ % curl --location 'http://127.0.0.1:8000/book/list' \
--header 'token: acc096ff-b82f-4836-a851-b6ca43ece8b8'
{"code":"90200","data":[],"msg":"查询书籍列表成功"}

//这里没有加token
fei@feideMacBook-Pro ~ % curl --location 'http://127.0.0.1:8000/book/add' \
--header 'token: xxxx' \
--header 'Content-Type: application/json' \
--data '{
"name":"三国",
"desc":"打仗啦",
"users":[
{
"id":6
}
]
}'
{"code":90403,"data":null,"msg":"The token is incorrect"}

fei@feideMacBook-Pro ~ % curl --location 'http://127.0.0.1:8000/book/add' \
--header 'token: acc096ff-b82f-4836-a851-b6ca43ece8b8' \
--header 'Content-Type: application/json' \
--data '{
"name":"三国",
"desc":"打仗啦",
"users":[
{
"id":6
}
]
}'
{"code":"90200","data":"三国 书籍添加成功","msg":"添加书籍成功"}

//再次获取书籍列表
fei@feideMacBook-Pro ~ % curl --location 'http://127.0.0.1:8000/book/list' \
--header 'token: acc096ff-b82f-4836-a851-b6ca43ece8b8'
{
"code": "90200",
"data": [{
"id": 20,
"name": "三国",
"desc": "打仗啦",
"Users": [{
"id": 6,
"username": "maxbit",
"password": "1234567",
"token": "acc096ff-b82f-4836-a851-b6ca43ece8b8",
"Books": null
}]
}],
"msg": "查询书籍列表成功"
}

//这里有个bug,GORM关联查询吧账号密码也查出来了😂 记个TODO

其他接口测试 略

更新:

1
2
3
4
//同时加载与用户相关联的 Users 数据。通过select选择输出的字段
tx := BookDAO.db.Preload("Users", func(db *gorm.DB) *gorm.DB {
return db.Select("id, username")
}).Find(&books)

测试:

1
2
3
4
~/go/src ❯ curl 'http://127.0.0.1:8000/book/list' \                               
--header 'token: 28b0ae49-e332-414d-8365-535d8a755830'

{"code":"90200","data":[{"id":1,"name":"三国","desc":"打仗啦","Users":[{"id":1,"username":"maxbit","password":"","token":"","Books":null}]}],"msg":"查询书籍列表成功"}