types - golang中的json-rpc,id为字符串

标签 types go json-rpc

我还是个新手。

我使用这个包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, &params, &reply, "application/json",
            gjson.EncodeClientRequest, DecodeClientResponse)

我觉得这很丑,有什么办法可以做得更好吗?

谢谢

最佳答案

json-rpc v 1.0 指定:

id - The request id. This can be of any type. It is used to match the response with the request that it is replying to.

也就是说,id 可以是任何内容(甚至是数组),并且服务器响应应该包含相同的 id 值和类型,但在您的情况下它不会这样做。因此,与您通信的服务器没有正确完成其工作,并且没有遵循 json-rpc v 1.0 规范。

所以,是的,您需要执行“丑陋”的解决方案,并为这个“损坏”的服务器创建一个新的解码器函数。 Jeremy Wall 的建议有效(但 int 应该更改为 uint64),并且至少应该让您避免使用 string 作为类型。

编辑

我不太了解 httprpc 包,无法知道它如何处理 Id 值。但如果您想要字符串或整数,您应该能够将 clientResponse 中的 Id 设置为:

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

关于types - golang中的json-rpc,id为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15713983/

相关文章:

C#如何获取正在设置的属性的名称

c - 关于类型,c 中的 `int (*)(int)` 是什么意思?

go - 反射(reflect),分配一个指针结构值

JSON RPC - "id"有何用途?

javascript - 从服务器端发送 "message"到客户端

sql-server - 选择 SQL Server 数据类型以获得最大速度

scala - 复合类型的意外行为

http - go 似乎不尊重持久连接设置

go - 为什么 Go 的 rand 包中的 Int63n 会这样调用它?

java - 如何处理 Java HTTP Server 上不匹配/不需要的或有效的请求?