/
json_api_common.go
259 lines (222 loc) · 5.48 KB
/
json_api_common.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package client
import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strings"
"golang.org/x/net/context"
"github.com/keybase/cli"
"github.com/keybase/client/go/libcmdline"
"github.com/keybase/client/go/libkb"
)
// ErrInvalidOptions is returned when the options aren't valid.
type ErrInvalidOptions struct {
method string
version int
err error
}
func (e ErrInvalidOptions) Error() string {
return fmt.Sprintf("invalid %s v%d options: %s", e.method, e.version, e.err)
}
type ErrInvalidMethod struct {
name string
version int
}
func (e ErrInvalidMethod) Error() string {
return fmt.Sprintf("invalid v%d method %q", e.version, e.name)
}
type ErrInvalidVersion struct {
version int
}
func (e ErrInvalidVersion) Error() string {
return fmt.Sprintf("invalid version %d", e.version)
}
type ErrInvalidJSON struct {
message string
}
func (e ErrInvalidJSON) Error() string {
return fmt.Sprintf("invalid JSON: %s", e.message)
}
// Call represents a JSON api call.
type Call struct {
Jsonrpc string
ID int
Method string
Params Params
}
// Params represents the `params` portion of the JSON api call.
type Params struct {
Version int
Options json.RawMessage
}
// CallError is the result when there is an error.
type CallError struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
// Reply is returned with the results of processing a Call.
type Reply struct {
Jsonrpc string `json:"jsonrpc,omitempty"`
ID int `json:"id,omitempty"`
Error *CallError `json:"error,omitempty"`
Result interface{} `json:"result,omitempty"`
}
// Checker implementations can check their options for errors.
type Checker interface {
Check() error
}
// cmdAPI contains common functionality for json api commands
type cmdAPI struct {
indent bool
inputFile string
outputFile string
message string
}
func newCmdAPI(cl *libcmdline.CommandLine, cmd libcmdline.Command, usage, description string) cli.Command {
return cli.Command{
Name: "api",
Usage: usage,
Action: func(c *cli.Context) {
cl.ChooseCommand(cmd, "api", c)
},
Flags: []cli.Flag{
cli.BoolFlag{
Name: "p, pretty",
Usage: "Output pretty (indented) JSON.",
},
cli.StringFlag{
Name: "m",
Usage: "Specify JSON as string instead of stdin",
},
cli.StringFlag{
Name: "i, infile",
Usage: "Specify JSON input file (stdin default)",
},
cli.StringFlag{
Name: "o, outfile",
Usage: "Specify output file (stdout default)",
},
},
Description: description,
}
}
func (c *cmdAPI) ParseArgv(ctx *cli.Context) error {
if len(ctx.Args()) != 0 {
return errors.New("api takes no arguments")
}
c.indent = ctx.Bool("pretty")
c.inputFile = ctx.String("infile")
c.outputFile = ctx.String("outfile")
c.message = ctx.String("m")
if len(c.message) > 0 && len(c.inputFile) > 0 {
return errors.New("specify -m or -i, but not both")
}
return nil
}
func (c *cmdAPI) SetMessage(m string) {
c.message = m
}
func (c *cmdAPI) SetOutputFile(f string) {
c.outputFile = f
}
func (c *cmdAPI) GetUsage() libkb.Usage {
return libkb.Usage{
API: true,
KbKeyring: true,
Config: true,
}
}
type handler interface {
handle(ctx context.Context, c Call, w io.Writer) error
}
func (c *cmdAPI) runHandler(h handler) (err error) {
w := os.Stdout
defer func() {
if err != nil {
err = encodeErr(Call{}, err, w, false)
}
}()
if len(c.outputFile) > 0 {
f, err := os.Create(c.outputFile)
if err != nil {
return err
}
defer f.Close()
w = f
}
r := io.Reader(os.Stdin)
if len(c.message) > 0 {
r = strings.NewReader(c.message)
} else if len(c.inputFile) > 0 {
f, err := os.Open(c.inputFile)
if err != nil {
return err
}
defer f.Close()
r = f
}
return c.decode(context.Background(), r, w, h)
}
func (c *cmdAPI) decode(ctx context.Context, r io.Reader, w io.Writer, h handler) (err error) {
dec := json.NewDecoder(r)
var call Call
defer func() {
if err != nil {
err = encodeErr(call, err, w, false)
}
}()
for {
if err := dec.Decode(&call); err == io.EOF {
break
} else if err != nil {
if err == io.ErrUnexpectedEOF {
return ErrInvalidJSON{message: "expected more JSON in input"}
}
return err
}
if err := h.handle(ctx, call, w); err != nil {
if err = encodeErr(call, err, w, false); err != nil {
return err
}
}
}
return nil
}
// encodeResult JSON encodes a successful result to the wr writer.
func encodeResult(call Call, result interface{}, wr io.Writer, indent bool) error {
reply := Reply{
Result: result,
}
return encodeReply(call, reply, wr, indent)
}
// encodeErr JSON encodes an error.
func encodeErr(call Call, err error, wr io.Writer, indent bool) error {
reply := Reply{Error: &CallError{Message: err.Error()}}
return encodeReply(call, reply, wr, indent)
}
// encodeReply JSON encodes all replies.
func encodeReply(call Call, reply Reply, wr io.Writer, indent bool) error {
// copy jsonrpc fields from call to reply
reply.Jsonrpc = call.Jsonrpc
reply.ID = call.ID
enc := json.NewEncoder(wr)
if indent {
enc.SetIndent("", " ")
}
return enc.Encode(reply)
}
// unmarshalOptions unmarshals any options in Call into opts,
// and verify they pass the Checker checks.
func unmarshalOptions(c Call, opts Checker) error {
if len(c.Params.Options) == 0 {
// still check the options in case any fields are required.
return opts.Check()
}
if err := json.Unmarshal(c.Params.Options, opts); err != nil {
return err
}
return opts.Check()
}