假设我在服务器上有以下Go结构
type account struct {
Name string
Balance int
}
Run Code Online (Sandbox Code Playgroud)
我想在传入的请求上调用json.Decode来将其解析为一个帐户.
var ac account
err := json.NewDecoder(r.Body).Decode(&ac)
Run Code Online (Sandbox Code Playgroud)
如果客户端发送以下请求:
{
"name": "test@example.com",
"balance": "3"
}
Run Code Online (Sandbox Code Playgroud)
Decode()将返回以下错误:
json: cannot unmarshal string into Go value of type int
Run Code Online (Sandbox Code Playgroud)
现在可以将其解析为"你为Balance发送了一个字符串,但你真的应该发送一个整数",但这很棘手,因为你不知道字段名称.如果请求中有很多字段,那么它也会变得更加棘手 - 您不知道哪个字段无法解析.
在Go中获取传入请求的最佳方法是什么,并为请求中的任意数量的整数字段返回错误消息"Balance必须是字符串"?
这里似乎提供了一个仅在 Go 中解决此问题的实现。
type account struct {
Name string
Balance int `json:",string"`
}
Run Code Online (Sandbox Code Playgroud)
在我看来,更正确和可持续的方法是用 JavaScript 之类的东西创建一个客户端库,并将其发布到 NPM 注册表中以供其他人使用(私有存储库也会以同样的方式工作)。通过提供这个库,您可以以有意义的方式为消费者定制 API,并防止错误渗透到您的主程序中。