You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
2.0 KiB
76 lines
2.0 KiB
9 years ago
|
// Copyright 2009 The Go Authors. All rights reserved.
|
||
9 years ago
|
// Copyright 2012 The Gorilla Authors. All rights reserved.
|
||
9 years ago
|
// Use of this source code is governed by a BSD-style
|
||
|
// license that can be found in the LICENSE file.
|
||
|
|
||
9 years ago
|
package json2
|
||
9 years ago
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"io"
|
||
|
"math/rand"
|
||
|
)
|
||
|
|
||
|
// ----------------------------------------------------------------------------
|
||
|
// Request and Response
|
||
|
// ----------------------------------------------------------------------------
|
||
|
|
||
|
// clientRequest represents a JSON-RPC request sent by a client.
|
||
|
type clientRequest struct {
|
||
9 years ago
|
// JSON-RPC protocol.
|
||
|
Version string `json:"jsonrpc"`
|
||
|
|
||
9 years ago
|
// A String containing the name of the method to be invoked.
|
||
|
Method string `json:"method"`
|
||
9 years ago
|
|
||
9 years ago
|
// Object to pass as request parameter to the method.
|
||
9 years ago
|
Params interface{} `json:"params"`
|
||
|
|
||
9 years ago
|
// 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 uint64 `json:"id"`
|
||
|
}
|
||
|
|
||
|
// clientResponse represents a JSON-RPC response returned to a client.
|
||
|
type clientResponse struct {
|
||
9 years ago
|
Version string `json:"jsonrpc"`
|
||
|
Result *json.RawMessage `json:"result"`
|
||
|
Error *json.RawMessage `json:"error"`
|
||
9 years ago
|
}
|
||
|
|
||
|
// EncodeClientRequest encodes parameters for a JSON-RPC client request.
|
||
|
func EncodeClientRequest(method string, args interface{}) ([]byte, error) {
|
||
|
c := &clientRequest{
|
||
9 years ago
|
Version: "2.0",
|
||
|
Method: method,
|
||
|
Params: args,
|
||
|
Id: uint64(rand.Int63()),
|
||
9 years ago
|
}
|
||
|
return json.Marshal(c)
|
||
|
}
|
||
|
|
||
|
// DecodeClientResponse decodes the response body of a client request into
|
||
|
// the interface reply.
|
||
|
func DecodeClientResponse(r io.Reader, reply interface{}) error {
|
||
|
var c clientResponse
|
||
|
if err := json.NewDecoder(r).Decode(&c); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
if c.Error != nil {
|
||
9 years ago
|
jsonErr := &Error{}
|
||
|
if err := json.Unmarshal(*c.Error, jsonErr); err != nil {
|
||
|
return &Error{
|
||
|
Code: E_SERVER,
|
||
|
Message: string(*c.Error),
|
||
|
}
|
||
|
}
|
||
|
return jsonErr
|
||
9 years ago
|
}
|
||
9 years ago
|
|
||
9 years ago
|
if c.Result == nil {
|
||
9 years ago
|
return ErrNullResult
|
||
9 years ago
|
}
|
||
9 years ago
|
|
||
9 years ago
|
return json.Unmarshal(*c.Result, reply)
|
||
|
}
|