package jsonrpc2
import (
"encoding/json"
"fmt"
"strconv"
)
const (
CodeUnknownError = -32001
CodeParseError = -32700
CodeInvalidRequest = -32600
CodeMethodNotFound = -32601
CodeInvalidParams = -32602
CodeInternalError = -32603
CodeServerOverloaded = -32000
)
type WireRequest struct {
VersionTag VersionTag `json:"jsonrpc"`
Method string `json:"method"`
Params *json.RawMessage `json:"params,omitempty"`
ID *ID `json:"id,omitempty"`
}
type WireResponse struct {
VersionTag VersionTag `json:"jsonrpc"`
Result *json.RawMessage `json:"result,omitempty"`
Error *Error `json:"error,omitempty"`
ID *ID `json:"id,omitempty"`
}
type Error struct {
Code int64 `json:"code"`
Message string `json:"message"`
Data *json.RawMessage `json:"data"`
}
type VersionTag struct{}
type ID struct {
Name string
Number int64
}
func (err *Error) Error() string {
if err == nil {
return ""
}
return err.Message
}
func (VersionTag) MarshalJSON() ([]byte, error) {
return json.Marshal("2.0")
}
func (VersionTag) UnmarshalJSON(data []byte) error {
version := ""
if err := json.Unmarshal(data, &version); err != nil {
return err
}
if version != "2.0" {
return fmt.Errorf("Invalid RPC version %v", version)
}
return nil
}
func (id *ID) String() string {
if id == nil {
return ""
}
if id.Name != "" {
return strconv.Quote(id.Name)
}
return "#" + strconv.FormatInt(id.Number, 10)
}
func (id *ID) MarshalJSON() ([]byte, error) {
if id.Name != "" {
return json.Marshal(id.Name)
}
return json.Marshal(id.Number)
}
func (id *ID) UnmarshalJSON(data []byte) error {
*id = ID{}
if err := json.Unmarshal(data, &id.Number); err == nil {
return nil
}
return json.Unmarshal(data, &id.Name)
}