api 数据返回过滤不需要的字段

2020-05-17 12:41:15 +08:00
 Wenco

目前在用 gin+gorm 写一个小玩意,遇到这样的情况:

为了代码复用及写起来方便,基本都是用的 orm select *

有时候面向前台的接口不方便展示数据集中的某个字段,但是面向后端的又需要

这应该是前后端分离都会遇到的吧,请教各位大佬,比较好的解决方案是什么?

7334 次点击
所在节点    Go 编程语言
44 条回复
siteshen
2020-05-18 16:29:09 +08:00
@Wenco NewUserResponse 是其他语言中的构造函数,这样对生成的 UserResponse 可控(甚至 UserResponse 可以设计为 private 的 userResponse )。

UserResponse 也是可以复用的,下面这个例子就会复用 BasicUser 。
用户列表可能就只需要 BasicUser (用户名、头像),
查看用户详情时可能需要 UserDetail (BasicUser + 粉丝数、文章数),
查看自己的详情时可能需要 Me ( UserDetail + 收入 + 草稿箱中的文章数)。


struct BasicUser {
username string
avatar url
}

// API readUser
struct UserDetail {
UserResponse
bio string
location string
n_follower int
n_following int
n_posts int
}

// 用户查看自己信息的时
struct Me {
UserDetail
n_fav_posts int
total_cost double
total_income double
n_draft_posts int
}

// API listUser
struct UserList {
users BasicUser[]
}
asAnotherJack
2020-05-19 11:37:03 +08:00
https://colobu.com/2017/06/21/json-tricks-in-Go/
刚好前段时间忘了在哪收藏的一篇文章,有楼主需要的
Wenco
2020-05-19 13:32:46 +08:00
@asAnotherJack 感谢,很有用!
JackyCDK
2020-05-21 14:41:08 +08:00
其实对 password 字段 omitempty 然后在 response 时直接给它赋值为空就完事了...我
@JackyCDK #11 的回复似乎是有问题的,我当时没查证,抱歉。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/672543

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX