go-todo-api/dto/README.md
2025-12-02 18:58:25 +08:00

15 lines
740 B
Markdown
Raw Permalink 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.

# 使用 DTO数据传输对象
你完全抓住了我们在处理 注册/登录 过程中遇到的一个常见的 Go Web 开发陷阱,这和我们在 models/user.go 中设置的 标签冲突 有关。
🚨 标签冲突的困境
你的目标是:
输入时 (注册/登录): 必须读取 JSON 中的明文密码,所以需要 json:"password"。
输出时 (防止信息泄露): 必须阻止密码哈希值被 JSON 序列化并返回给客户端,所以需要 json:"-"。
不幸的是,一个字段不能同时拥有两个不同的 json 标签。
解决这个困境的最佳和最专业的做法是 为输入/输出定义不同的结构体,将 models.User 结构体专门用于数据库操作,而将输入/输出交给 DTO