Remove unnecessary pointer usage.
Make sure the p2p stream is closed eventually License: MIT Signed-off-by: Ian Preston <ianopolous@protonmail.com>
Dr Ian Preston committed
Oct 3, 2018 at 19:20 UTC
c67d2b41862cb6f74c3fc5f49be9b0fbe4b24e66
1 file changed
+32
-7
core/corehttp/proxy.go
+32
-7
@@ -4,6 +4,7 @@ import (
4
"bufio"
5
"fmt"
6
"net"
7
+ "io"
8
"net/http"
9
"net/http/httputil"
10
"strings"
@@ -34,7 +35,7 @@ func ProxyOption() ServeOption {
35
return
36
}
37
//send proxy request and response to client
37
- newReverseHTTPProxy(parsedRequest, &stream).ServeHTTP(w, request)
38
+ newReverseHTTPProxy(parsedRequest, stream).ServeHTTP(w, request)
39
})
40
return mux, nil
41
}
@@ -71,7 +72,7 @@ func handleError(w http.ResponseWriter, msg string, err error, code int) {
72
log.Warningf("server error: %s: %s", err)
73
}
74
74
-func newReverseHTTPProxy(req *proxyRequest, streamToPeer *inet.Stream) *httputil.ReverseProxy {
75
+func newReverseHTTPProxy(req *proxyRequest, streamToPeer inet.Stream) *httputil.ReverseProxy {
76
director := func(r *http.Request) {
77
r.URL.Path = req.httpPath //the scheme etc. doesn't matter
78
}
@@ -82,15 +83,28 @@ func newReverseHTTPProxy(req *proxyRequest, streamToPeer *inet.Stream) *httputil
83
}
84
85
type roundTripper struct {
85
- stream *inet.Stream
86
+ stream inet.Stream
87
+}
88
+
89
+// we wrap the response body and close the stream
90
+// only when it's closed.
91
+type respBody struct {
92
+ io.ReadCloser
93
+ stream inet.Stream
94
+}
95
+
96
+// Closes the response's body and the connection.
97
+func (rb *respBody) Close() error {
98
+ rb.stream.Close()
99
+ return rb.ReadCloser.Close()
100
}
101
102
func (rt *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
103
104
sendRequest := func() {
91
- err := req.Write(*rt.stream)
105
+ err := req.Write(rt.stream)
106
if err != nil {
93
- (*(rt.stream)).Close()
107
+ rt.stream.Close()
108
}
109
if req.Body != nil {
110
req.Body.Close()
@@ -98,6 +112,17 @@ func (rt *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
112
}
113
//send request while reading response
114
go sendRequest()
101
- s := bufio.NewReader(*rt.stream)
102
- return http.ReadResponse(s, req)
115
+ s := bufio.NewReader(rt.stream)
116
+
117
+ resp, err := http.ReadResponse(s, req)
118
+ if err != nil {
119
+ return resp, err
120
+ }
121
+
122
+ resp.Body = &respBody{
123
+ ReadCloser: resp.Body,
124
+ stream: rt.stream,
125
+ }
126
+
127
+ return resp, nil
128
}