我正在编写一个接受 json 的 http 服务器。有一个结构:
type AuthModel struct {
Username string
Password string
}
假设用户发送以下 json:
{
"username": "user",
"password": 1234
}
任务是验证它并向客户指出他的错误。验证后,我期望得到:Invalid password type. Allow: string或者类似的东西,没关系,主要是弄清楚客户的错误是什么。
当我尝试将此 json 解析为使用json.Unmarshal它的结构时,我收到此错误:json: cannot unmarshal number into Go struct field AuthModel.password of type string. 我不会将此类文本返回给客户。我认为尝试解析它是愚蠢的(尽管如果没有其他方法......)。如果我忽略此错误,则结构将仅包含一个空字段password,并且不清楚问题是它的类型错误或根本没有填充。
如何在这里进行?有现成的解决方案吗?
最好在这些情况下返回
http.StatusBadRequest,尝试go-playground/validator来验证数据。验证器允许您验证来自用户的传入数据,例如,密码必须大于 10 个字符结构中的 Password 变量是字符串类型,而您正在发送带有 int 类型的 Password 变量的 json。
1 解决方案: 将结构更改为:
2 解决方法: 更改发送的json: