This repository was archived by the owner on Jan 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresponse.go
71 lines (60 loc) · 1.76 KB
/
response.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
package fastjsonrpc
import (
"encoding/json"
"github.com/valyala/fastjson"
)
//go:generate go get -u github.com/valyala/quicktemplate/qtc
//go:generate qtc -dir=.
func (ctx *RequestCtx) writeString(s string) {
_, _ = ctx.response.WriteString(s)
}
// SetError writes JSON-RPC response with error.
//
// It overwrites previous calls of SetResult and SetError.
func (ctx *RequestCtx) SetError(err *Error) {
if len(ctx.id) == 0 {
return
}
ctx.response.Reset()
if err.Data == nil {
writeresponseWithError(ctx.response, ctx.id, err.Code, err.Message, nil)
return
}
switch v := err.Data.(type) {
case *fastjson.Value:
buf := ctx.bytebufferpool.Get()
writeresponseWithError(ctx.response, ctx.id, err.Code, err.Message, v.MarshalTo(buf.B))
ctx.bytebufferpool.Put(buf)
case []byte:
writeresponseWithError(ctx.response, ctx.id, err.Code, err.Message, v)
default:
buf := ctx.bytebufferpool.Get()
_ = json.NewEncoder(buf).Encode(err.Data)
writeresponseWithError(ctx.response, ctx.id, err.Code, err.Message, buf.B)
ctx.bytebufferpool.Put(buf)
}
}
// SetResult writes JSON-RPC response with result.
//
// It overwrites previous calls of SetResult and SetError.
//
// result may be *fastjson.Value, []byte, or interface{} (slower).
func (ctx *RequestCtx) SetResult(result interface{}) {
if len(ctx.id) == 0 {
return
}
ctx.response.Reset()
switch v := result.(type) {
case *fastjson.Value:
buf := ctx.bytebufferpool.Get()
writeresponseWithResult(ctx.response, ctx.id, v.MarshalTo(buf.B))
ctx.bytebufferpool.Put(buf)
case []byte:
writeresponseWithResult(ctx.response, ctx.id, v)
default:
buf := ctx.bytebufferpool.Get()
_ = json.NewEncoder(buf).Encode(result)
writeresponseWithResult(ctx.response, ctx.id, buf.B)
ctx.bytebufferpool.Put(buf)
}
}