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条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题