-
Notifications
You must be signed in to change notification settings - Fork 21
/
client_conn.go
118 lines (106 loc) · 2.45 KB
/
client_conn.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
111
112
113
114
115
116
117
118
// Copyright 2013-14, Amahi. All rights reserved.
// Use of this source code is governed by the
// license that can be found in the LICENSE file.
// client connection related functions
package spdy
import (
"bytes"
"errors"
"net"
"net/http"
"time"
)
func handle(err error) {
if err != nil {
panic(err)
}
}
// NewRecorder returns an initialized ResponseRecorder.
func NewRecorder() *ResponseRecorder {
return &ResponseRecorder{
HeaderMap: make(http.Header),
Body: new(bytes.Buffer),
Code: 200,
}
}
// Header returns the response headers.
func (rw *ResponseRecorder) Header() http.Header {
m := rw.HeaderMap
if m == nil {
m = make(http.Header)
rw.HeaderMap = m
}
return m
}
// Write always succeeds and writes to rw.Body.
func (rw *ResponseRecorder) Write(buf []byte) (int, error) {
if !rw.wroteHeader {
rw.WriteHeader(200)
}
if rw.Body != nil {
len, err := rw.Body.Write(buf)
return len, err
} else {
rw.Body = new(bytes.Buffer)
len, err := rw.Body.Write(buf)
return len, err
}
return len(buf), nil
}
// WriteHeader sets rw.Code.
func (rw *ResponseRecorder) WriteHeader(code int) {
if !rw.wroteHeader {
rw.Code = code
}
rw.wroteHeader = true
}
//returns a client that reads and writes on c
func NewClientConn(c net.Conn) (*Client, error) {
session := NewClientSession(c)
go session.Serve()
return &Client{cn: c, ss: session}, nil
}
//returns a client with tcp connection created using net.Dial
func NewClient(addr string) (*Client, error) {
conn, err := net.Dial("tcp", addr)
if err != nil {
return &Client{}, err
}
session := NewClientSession(conn)
go session.Serve()
return &Client{cn: conn, ss: session}, nil
}
//to get a response from the client
func (c *Client) Do(req *http.Request) (*http.Response, error) {
rr := NewRecorder()
err := c.ss.NewStreamProxy(req, rr)
if err != nil {
return &http.Response{}, err
}
resp := &http.Response{
StatusCode: rr.Code,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Body: &readCloser{rr.Body},
ContentLength: int64(rr.Body.Len()),
Header: rr.Header(),
}
return resp, nil
}
func (c *Client) Close() error {
if c.cn == nil {
err := errors.New("No connection to close")
return err
}
err := c.cn.Close()
return err
}
func (c *Client) Ping(d time.Duration) (pinged bool, err error) {
if c.cn == nil {
err := errors.New("No connection estabilished to server")
return false, err
}
ping := c.ss.Ping(d)
return ping, nil
}