-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_conn.go
125 lines (101 loc) · 2.26 KB
/
http_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
119
120
121
122
123
124
125
package http4git
import (
"fmt"
"net/http"
"strings"
"github.com/bitwormhole/gitlib/git/network/pktline"
)
type httpConn struct {
context *connectionContext
url string
service string
method string
// io
requestFIFO ByteFIFO
requestContentType string
requestTx pktline.WriterCloser
responseRx pktline.ReaderCloser
// status
started bool
starting bool
stopped bool
stopping bool
}
func (inst *httpConn) _Impl() pktline.Connection {
return inst
}
func (inst *httpConn) init(method string) {
method = strings.TrimSpace(method)
method = strings.ToUpper(method)
if method == "" {
method = http.MethodGet
}
inst.method = method
}
func (inst *httpConn) Close() error {
inst.stopping = true
return nil
}
func (inst *httpConn) GetGroup() pktline.ConnectionGroup {
return nil
}
func (inst *httpConn) GetAttribute(name string) any {
return nil
}
func (inst *httpConn) SetAttribute(name string, value any) {
}
func (inst *httpConn) GetParams() *pktline.ConnParams {
return nil
}
func (inst *httpConn) GetService() string {
return inst.service
}
// 创建新的附加连接
func (inst *httpConn) NewConnection(p *pktline.ConnParams) (pktline.Connection, error) {
return inst.context.open(p)
}
func (inst *httpConn) OpenWriter(contentType string) (pktline.WriterCloser, error) {
tx := inst.requestTx
if tx != nil {
return tx, nil
}
fifo, err := OpenByteFIFO()
if err != nil {
return nil, err
}
tx = pktline.NewWriterCloser(fifo, true)
inst.requestFIFO = fifo
inst.requestTx = tx
inst.requestContentType = contentType
return tx, nil
}
func (inst *httpConn) OpenReader() (pktline.ReaderCloser, string, error) {
url := inst.url
method := inst.method
body1 := inst.requestFIFO
client := http.DefaultClient
req, err := http.NewRequest(method, url, body1)
if err != nil {
return nil, "", err
}
resp, err := client.Do(req)
if err != nil {
return nil, "", err
}
code := resp.StatusCode
body2 := resp.Body
ctype := resp.Header.Get("Content-Type")
defer func() {
if body2 != nil {
body2.Close()
}
}()
if code != http.StatusOK {
return nil, "", fmt.Errorf("HTTP %v", resp.Status)
}
rx := pktline.NewReaderCloser(body2, true)
inst.responseRx = rx
inst.started = true
body2 = nil
return rx, ctype, nil
}