forked from devsisters/goquic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
110 lines (92 loc) · 2.49 KB
/
client.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
package goquic
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
)
type QuicRoundTripper struct {
conns map[string]*Conn
keepConnection bool
}
type badStringError struct {
what string
str string
}
func NewRoundTripper(keepConnection bool) *QuicRoundTripper {
return &QuicRoundTripper{
conns: make(map[string]*Conn),
keepConnection: keepConnection,
}
}
func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) }
func (q *QuicRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
if request.Method != "GET" {
return nil, errors.New("non-GET request is not supported yet. Sorry.")
// TODO(hodduc): POST / HEAD / PUT support
}
var conn *Conn
var exists bool
conn, exists = q.conns[request.Host]
if !q.keepConnection || !exists {
conn_new, err := Dial("udp4", request.Host)
if err != nil {
return nil, err
}
q.conns[request.Host] = conn_new
conn = conn_new
}
st := conn.CreateStream()
header := make(http.Header)
for k, v := range request.Header {
for _, vv := range v {
header.Add(k, vv)
}
}
header.Set(":host", request.Host)
header.Set(":version", request.Proto)
header.Set(":method", request.Method)
header.Set(":path", request.URL.RequestURI())
header.Set(":scheme", request.URL.Scheme)
if request.Method == "GET" {
st.WriteHeader(header, true)
}
recvHeader, err := st.ReadHeader()
if err != nil {
return nil, err
}
resp := &http.Response{}
resp.Status = recvHeader.Get(":status")
f := strings.SplitN(resp.Status, " ", 3)
if len(f) < 1 {
return nil, &badStringError{"malformed HTTP response", resp.Status}
}
resp.StatusCode, err = strconv.Atoi(f[0])
if err != nil {
return nil, &badStringError{"malformed HTTP status code", f[0]}
}
resp.ProtoMajor, resp.ProtoMinor = 2, 0
resp.Header = recvHeader
resp.ContentLength, err = strconv.ParseInt(recvHeader.Get("content-length"), 10, 64)
if err != nil {
resp.ContentLength = -1
}
resp.Request = request
if q.keepConnection {
resp.Body = ioutil.NopCloser(st)
} else {
// XXX(hodduc): "conn" should be closed after the user reads all response body, so
// it's hard to determine when to close "conn". So we read all response body prematurely.
// If response is very big, this could be problematic. (Consider using runtime.finalizer())
body, err := ioutil.ReadAll(st)
if err != nil {
return nil, err
}
resp.Body = ioutil.NopCloser(bytes.NewBuffer(body))
conn.Close()
}
return resp, nil
}