dongzhanjuan5141 2013-03-30 01:41
浏览 83
已采纳

Golang中的json-rpc,id为字符串

I'm fairly new to go.

I use this package https://github.com/kdar/httprpc to do my json-rpc v 1.0 requests (as golang only implements 2.0)

I have a problem, this server i'm calling return the "id" as a string, like

"id":"345"

instead of

"id":345

The only way I found was to redefine clientResponse using string instead of uint64

type clientResponse struct {
    Result *json.RawMessage `json:"result"`
    Error  interface{}      `json:"error"`
    Id     string           `json:"id"`
}

and to redefine the exacte same DecodeClientResponse function to use my clientResponse

and instead of CallJson, I call (DecodeClientResponse instead of gjson.DecodeClientResponse):

httprpc.CallRaw(address, method, &params, &reply, "application/json",
            gjson.EncodeClientRequest, DecodeClientResponse)

I find this quite ugly, is there any way to do better ?

Thanks

  • 写回答

2条回答 默认 最新

  • douxiji8707 2013-03-31 19:23
    关注

    The json-rpc v 1.0 specifies that:

    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.

    That is, id can be anything (even an array), and the server response should contain the same value and type for id, which in your case it doesn't do. So, the server you communicate with is not doing its job correctly, and is not following the json-rpc v 1.0 specs.

    So, yes, you need to do the "ugly" solution and create a new decoder function for this 'broken' server. Jeremy Wall's suggestion works (but int should be changed to uint64) and should at least make you avoid using string as type.

    Edit

    I don't know the httprpc package enough to know how it handles the Id value. But if you want either string or int, you should be able to set Id in clientResponse to:

    Id interface{} `json:"id"`
    

    When checking the value in Id you use a type switch:

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?