-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathresponse.go
More file actions
128 lines (107 loc) · 2.33 KB
/
response.go
File metadata and controls
128 lines (107 loc) · 2.33 KB
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
package main
import (
"io"
"net/http"
"reflect"
"strconv"
"github.com/30x/gozerian/pipeline"
)
type response struct {
id uint32
cmds chan command
bodies chan []byte
resp *http.Response
request *request
origStatus int
origHeaders http.Header
origBody io.Reader
readStarted bool
}
func newResponse(id uint32, pd pipeline.Definition) *response {
r := response{
id: id,
cmds: make(chan command, commandQueueSize),
bodies: make(chan []byte, bodyQueueSize),
}
return &r
}
func (r *response) Commands() chan command {
return r.cmds
}
func (r *response) Bodies() chan []byte {
return r.bodies
}
func (r *response) Headers() http.Header {
return r.resp.Header
}
func (r *response) ResponseWritten() {
}
func (r *response) StartRead() {
// In this model, once body is read, we can no longer change headers or status.
// This limitation may be specific to nginx -- if so then we will make it
// configurable.
r.readStarted = true
r.flushHeaders()
}
func (r *response) begin(status uint32, rawHeaders string, req *request) error {
r.request = req
go r.startResponse(status, rawHeaders)
return nil
}
func (r *response) pollNB() string {
select {
case cmd := <-r.cmds:
return cmd.String()
default:
return ""
}
}
func (r *response) poll() string {
cmd := <-r.cmds
return cmd.String()
}
func (r *response) startResponse(status uint32, rawHeaders string) {
resp, err := parseHTTPResponse(status, rawHeaders)
if err != nil {
r.cmds <- createErrorCommand(err)
return
}
resp.Request = r.request.req
r.resp = resp
r.origStatus = resp.StatusCode
r.origHeaders = copyHeaders(resp.Header)
resp.Body = &requestBody{
handler: r,
}
r.origBody = resp.Body
rresp := &httpResponse{
handler: r,
}
r.request.pipe.ResponseHandlerFunc()(rresp, resp.Request, resp)
if !r.readStarted {
r.flushHeaders()
}
r.flushBody()
r.cmds <- command{id: DONE}
}
func (r *response) flushHeaders() {
if r.origStatus != r.resp.StatusCode {
staCmd := command{
id: WSTA,
msg: strconv.Itoa(r.resp.StatusCode),
}
r.cmds <- staCmd
}
if !reflect.DeepEqual(r.origHeaders, r.resp.Header) {
hdrCmd := command{
id: WHDR,
msg: serializeHeaders(r.resp.Header),
}
r.cmds <- hdrCmd
}
}
func (r *response) flushBody() {
if r.origBody != r.resp.Body {
readAndSend(r, r.resp.Body)
}
}