我很新。
我使用这个程序包https://github.com/kdar/httprpc来执行我的json-rpc v 1.0请求(因为golang仅实现2.0)
我有一个问题,我正在调用的服务器将“ id”作为字符串返回,例如
"id":"345"
代替
"id":345
我发现的唯一方法是使用字符串而不是uint64重新定义clientResponse
type clientResponse struct {
Result *json.RawMessage `json:"result"`
Error interface{} `json:"error"`
Id string `json:"id"`
}
并重新定义完全相同的DecodeClientResponse函数以使用我的clientResponse
而不是CallJson,我调用了(DecodeClientResponse而不是gjson.DecodeClientResponse):
httprpc.CallRaw(address, method, ¶ms, &reply, "application/json",
gjson.EncodeClientRequest, DecodeClientResponse)
我觉得这很丑,有什么办法可以做得更好?
谢谢
json-rpc v 1.0指定:
id-请求ID。可以是任何类型。它用于将响应与其正在响应的请求进行匹配。
也就是说,id
可以是任何值(甚至是数组),并且服务器响应应该包含与id相同的值和类型,在您的情况下则不这样做。因此,您与之通信的服务器未正确执行其工作,并且未遵循json-rpc v 1.0规范。
因此,是的,您需要执行“丑陋”的解决方案并为此“损坏的”服务器创建新的解码器功能。杰里米·沃尔(Jeremy Wall)的建议有效(但int
应更改为uint64
),至少应避免使用string
as类型。
编辑
我对httprpc
软件包的了解不足,无法知道它如何处理Id
价值。但是,如果要使用字符串或整数,则应该可以将ID设置clientResponse
为:
Id interface{} `json:"id"`
在检查值时,Id
请使用类型开关:
var id int
// response is of type clientResponse
switch t := response.Id.(type) {
default:
// Error. Bad type
case string:
var err error
id, err = strconv.Atoi(t)
if err != nil {
// Error. Not possible to convert string to int
}
case int:
id = t
}
// id now contains your value
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句