This repository has been archived by the owner on May 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathresponse.go
77 lines (68 loc) · 1.56 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
72
73
74
75
76
77
package synapse
import (
"github.com/tinylib/msgp/msgp"
)
const outPrealloc = 256
// A ResponseWriter is the interface through
// which Handlers write responses. Handlers can
// either return a body (through Send) or an
// error (through Error); whichever call is
// made first should 'win'. Subsequent calls
// to either method should no-op.
type ResponseWriter interface {
// Error sets an error status
// to be returned to the caller,
// along with an explanation
// of the error.
Error(Status, string)
// Send sets the body to be
// returned to the caller.
Send(msgp.Marshaler) error
}
// ResponseWriter implementation
type response struct {
out []byte // body
wrote bool // written?
_ [sizeofPtr - 1]byte // pad
}
func (r *response) resetLead() {
// we need to save the lead bytes
if cap(r.out) < leadSize {
r.out = make([]byte, leadSize, outPrealloc)
return
}
r.out = r.out[0:leadSize]
return
}
// base Error implementation
func (r *response) Error(s Status, expl string) {
if r.wrote {
return
}
r.wrote = true
r.resetLead()
r.out = msgp.AppendInt(r.out, int(s))
r.out = msgp.AppendString(r.out, expl)
}
// base Send implementation
func (r *response) Send(msg msgp.Marshaler) error {
if r.wrote {
return nil
}
r.wrote = true
var err error
r.resetLead()
r.out = msgp.AppendInt(r.out, int(StatusOK))
if msg != nil {
r.out, err = msg.MarshalMsg(r.out)
if err != nil {
return err
}
if len(r.out) > maxMessageSize {
return ErrTooLarge
}
return nil
}
r.out = msgp.AppendNil(r.out)
return nil
}