2013-03-30 32 views
2

我是相當新的去。golang中的json-rpc,字符串的id

我用這個包https://github.com/kdar/httprpc做我的JSON-RPC 1.0版的要求(如golang只實現2.0)

我有一個問題,這個服務器我打電話返回「ID」的字符串,如

"id":"345" 

,而不是

"id":345 

我發現的唯一辦法就是使用字符串來重新定義clientResponse而不是UINT64

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

,並重新定義exacte相同DecodeClientResponse功能用我clientResponse

和替代CallJson,我打電話(的gjson.DecodeClientResponse DecodeClientResponse代替):

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

我覺得這是很醜陋,有沒有辦法做得更好?

感謝

回答

2

的JSON-RPC V 1.0規定:

ID - 請求ID。這可以是任何類型。它用於將響應與它正在回覆的請求進行匹配。

也就是說,id可以是任何東西(甚至陣列),服務器的響應應該包含ID,它在你的情況下,它不會做同樣的價值和類型。因此,與您通信的服務器沒有正確地執行其工作,並且沒有遵循json-rpc v 1.0規範。

所以,是的,你需要做一個「醜陋」的解決方案,併爲這個'破損'的服務器創建一個新的解碼器功能。 Jeremy Wall的建議可行(但int應更改爲uint64),並且至少應該讓您避免使用string作爲類型。

編輯

我不知道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 
+0

感謝,併爲可能解碼int和字符串,就像int不起作用一樣,試試字符串。或者我應該這樣做:StringId string'json:「id」'和IntId uint64'json:「id」'? – vieux

+0

是的,這是可能的。我不知道'httprpc'包足以知道它如何處理'id'值。但是我編輯了答案,以顯示如何使用'interface {}'而不是字符串。 – ANisus

1

嘗試

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

    # Tell encoding/json that the field is 
    # encoded as a json string even though the type is int. 
    Id  int   `json:"id,string"` 
} 

只要庫是使用遮光罩這應該工作在編碼/ JSON。