gf icon indicating copy to clipboard operation
gf copied to clipboard

gf gen dao是否支持配置生成的entity的tag

Open tantalate opened this issue 5 months ago • 2 comments

我看很久以前有人提过,但是文档中没有找到如何设置

想问一下,gf gen dao 支持配置某些字段增加 json - 或者 omitempy 吗?比如 password, phone 这种不想返回给前端,但是又不想再 copy 一份 entity.User 结构体

Originally posted by @yahuian in #1639

tantalate avatar Jul 11 '25 02:07 tantalate

目前不支持的。

不过你可以新建一个文件,比如 user_json.goUser 结构体实现 MarshalJSON 方法,用于屏蔽敏感字段

func (u User) MarshalJSON() ([]byte, error) {
	type NewUser User

	newUser := NewUser(u)
	newUser.Password = ""

	return json.Marshal(newUser)
}

这种实现方式只会影响 序列化(go 转 JSON), 对反序列化(JSON 转 go)无影响,即不影响接收 JSON 中的 password 字段 ,会更好一些。

wufeng5702 avatar Aug 25 '25 09:08 wufeng5702

今天研究了很久,在不修改entity包的前提下,可能只能手动拷贝一份entity.User到model.User了,然后修改tag,缺点就是model.User无法同步数据库字段变化。

本来研究 model.User嵌入entity.User,然后自定义MarshalJSON结合 json omitempty实现字段隐藏,但是如果model.User被嵌入到比如model.UserWithRole这样的结构体,会导致model.UserWithRole无法正常序列化,所以该方法只能PASS掉了。

哎,没有好的办法,代码生成和这个需求有点冲突

keepeye avatar Sep 15 '25 13:09 keepeye