-
Notifications
You must be signed in to change notification settings - Fork 7
/
methods.go
107 lines (101 loc) · 3.88 KB
/
methods.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// Copyright 2018 Adam S Levy. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
package jsonrpc2
import (
"encoding/json"
"fmt"
"log"
"os"
)
// DebugMethodFunc controls whether additional debug information will be
// printed to stdout in the event of an InternalError when a MethodFunc is
// called. This can be helpful when troubleshooting MethodFuncs.
var DebugMethodFunc = false
var logger = log.New(os.Stdout, "", 0)
// MethodMap associates method names with MethodFuncs and is passed to
// HTTPRequestHandler() to generate a corresponding http.HandlerFunc.
type MethodMap map[string]MethodFunc
// MethodFunc is the function signature used for RPC methods. The raw JSON of
// the params of a valid Request is passed to the MethodFunc for further
// application specific unmarshaling and validation. When a MethodFunc is
// invoked by the handler, the params json.RawMessage, if not nil, is
// guaranteed to be valid JSON representing a structured JSON type. If the
// "params" field was omitted or was null, then nil is passed to the
// MethodFunc.
//
// A valid MethodFunc must return a not-nil interface{} that will not cause an
// error when passed to json.Marshal and will not marshal to null. If the
// underlying type of the returned interface{} is Error, then an Error Response
// will be returned to the client. Any return value that is not an Error will
// be used as the "result" field.
//
// If the MethodFunc returns an Error, then the Error must either use the
// InvalidParamsCode, or it must use an Error.Code that is outside of the
// reserved error code range. See ErrorCode.IsReserved() for more information.
//
// An invalid MethodFunc will result in an Internal Error to be returned to the
// client without revealing any information about the error. If you are getting
// InternalErrors from your MethodFunc, set DebugMethodFunc to true for
// additional debug output about the cause of the Internal Error.
type MethodFunc func(params json.RawMessage) interface{}
// call is used to safely call a method from within an http.HandlerFunc. call
// wraps the actual invocation of the method so that it can recover from panics
// and validate and sanitize the returned Response. If the method panics or
// returns an invalid Response, an InternalError response is returned.
func (method MethodFunc) call(params json.RawMessage) (res Response) {
var result interface{}
defer func() {
if err := recover(); err != nil {
res.Result = nil
res.Error = &InternalError
if DebugMethodFunc {
//res.Data = err
logger.Println(err)
logger.Printf("Params: %v", string(params))
logger.Printf("Return: %#v", result)
}
}
}()
result = method(params)
if result == nil {
panic("MethodFunc error: method returned nil")
}
// Check if this is an Error.
if methodErr, ok := result.(Error); ok {
// InvalidParamsCode is the only reserved ErrorCode MethodFuncs
// are allowed to use.
if methodErr.Code == InvalidParamsCode {
// Ensure the correct message is used.
methodErr.Message = InvalidParamsMessage
} else if methodErr.Code.IsReserved() {
panic("MethodFunc error: Error.Code is reserved")
}
if methodErr.Data != nil {
// Marshal the user provided Error.Data to catch any
// potential errors here.
data, err := json.Marshal(methodErr.Data)
if err != nil {
panic(fmt.Sprintf("MethodFunc error: Error.Data: %v", err))
}
// Omit null Data.
if string(data) == "null" {
methodErr.Data = nil
} else {
methodErr.Data = json.RawMessage(data)
}
}
res.Error = &methodErr
return
}
// Marshal the user provided Result to catch any potential errors here.
data, err := json.Marshal(result)
if err != nil {
panic(fmt.Sprintf("MethodFunc error: %v", err))
}
if string(data) == "null" {
panic(`MethodFunc error: Result marshalled to "null"`)
}
res.Result = json.RawMessage(data)
return
}