-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathdebug.go
56 lines (48 loc) · 1.25 KB
/
debug.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
package jsonrpc
import (
"net/http"
"reflect"
"github.com/goccy/go-json"
"github.com/invopop/jsonschema"
)
// A MethodReference is a reference of JSON-RPC method.
type MethodReference struct {
Name string `json:"name"`
Handler string `json:"handler"`
Params *jsonschema.Schema `json:"params,omitempty"`
Result *jsonschema.Schema `json:"result,omitempty"`
}
// ServeDebug views registered method list.
func (mr *MethodRepository) ServeDebug(w http.ResponseWriter, r *http.Request) {
ms := mr.Methods()
if len(ms) == 0 {
w.WriteHeader(http.StatusNotFound)
return
}
l := make([]*MethodReference, 0, len(ms))
for k, md := range ms {
l = append(l, makeMethodReference(k, md))
}
w.Header().Set(contentTypeKey, contentTypeValue)
if err := json.NewEncoder(w).EncodeContext(r.Context(), l); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func makeMethodReference(k string, md Metadata) *MethodReference {
mr := &MethodReference{
Name: k,
}
tv := reflect.TypeOf(md.Handler)
if tv.Kind() == reflect.Ptr {
tv = tv.Elem()
}
mr.Handler = tv.Name()
if md.Params != nil {
mr.Params = jsonschema.Reflect(md.Params)
}
if md.Result != nil {
mr.Result = jsonschema.Reflect(md.Result)
}
return mr
}